import {
  Entity,
  Column,
  ManyToOne,
  JoinColumn,
  Index,
  PrimaryGeneratedColumn,
  CreateDateColumn,
} from 'typeorm';
import { UserEntity } from './user.entity';

/**
 * PasswordResetEntity — one row per reset request.
 *
 * Token is never persisted in plaintext — only the SHA-256 hex
 * digest. Lookups happen by hash so a stolen DB dump can't be
 * redeemed. Row is single-use (used_at fills on first redemption)
 * and time-bound (expires_at enforced at lookup).
 *
 * Not extending BaseEntity because:
 *   - This table doesn't carry a single-tenant scope guarantee via
 *     CLS (the forgot-password endpoint is unauthenticated, no CLS
 *     context). We carry tenant_id explicitly and resolve it from
 *     the resolved user during the request handler instead.
 *   - We never soft-delete past tokens; they age out via
 *     used_at / expires_at and a periodic cleanup job. is_deleted
 *     stays for parity with the rest of the schema in case ops
 *     wants to suppress a row.
 */
@Entity('password_resets')
@Index('IDX_password_resets_token_hash', ['token_hash'], {
  unique: true,
  where: '"is_deleted" = false',
})
@Index('IDX_password_resets_user_active', ['user_id'], {
  where: '"used_at" IS NULL AND "is_deleted" = false',
})
export class PasswordResetEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid' })
  tenant_id: string;

  @ManyToOne(() => UserEntity, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'user_id' })
  user: UserEntity;

  @Column({ type: 'uuid' })
  user_id: string;

  /** SHA-256 hex digest of the raw token. Raw never persisted. */
  @Column({ type: 'varchar', length: 64 })
  token_hash: string;

  @Column({ type: 'timestamptz' })
  expires_at: Date;

  /** Filled with the consumption timestamp the moment the user
   *  successfully resets the password. Single-use enforcement. */
  @Column({ type: 'timestamptz', nullable: true })
  used_at: Date | null;

  /** Captured for the auth-event audit log (security.md A09). */
  @Column({ type: 'varchar', length: 45, nullable: true })
  request_ip: string | null;

  @Column({ type: 'text', nullable: true })
  request_user_agent: string | null;

  @CreateDateColumn({ type: 'timestamptz' })
  created_at: Date;

  @Column({ type: 'boolean', default: false })
  is_deleted: boolean;
}
