import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { User } from './user.entity.js';
import { Tenant } from './tenant.entity.js';

@Entity({ schema: 'auth', name: 'login_attempts' })
@Index('idx_login_attempts_email', ['email', 'createdAt'])
@Index('idx_login_attempts_ip', ['ipAddress', 'createdAt'])
@Index('idx_login_attempts_cleanup', ['createdAt'])
export class LoginAttempt {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  // Identification
  @Column({ type: 'varchar', length: 255, nullable: true })
  email: string | null;

  @Column({ type: 'inet', nullable: false, name: 'ip_address' })
  ipAddress: string;

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

  // Result
  @Column({ type: 'boolean', nullable: false })
  success: boolean;

  @Column({
    type: 'varchar',
    length: 100,
    nullable: true,
    name: 'failure_reason',
  })
  failureReason: string | null;

  // MFA
  @Column({ type: 'boolean', default: false, name: 'mfa_required' })
  mfaRequired: boolean;

  @Column({ type: 'boolean', nullable: true, name: 'mfa_passed' })
  mfaPassed: boolean | null;

  // Metadata
  @Column({ type: 'uuid', nullable: true, name: 'tenant_id' })
  tenantId: string | null;

  @Column({ type: 'uuid', nullable: true, name: 'user_id' })
  userId: string | null;

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

  // Relations
  @ManyToOne(() => Tenant, { nullable: true })
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant | null;

  @ManyToOne(() => User, { nullable: true })
  @JoinColumn({ name: 'user_id' })
  user: User | null;
}
