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: 'api_keys' })
@Index('idx_api_keys_lookup', ['keyIndex', 'isActive'], {
  where: 'is_active = TRUE',
})
@Index('idx_api_keys_expiration', ['expirationDate'], {
  where: 'expiration_date IS NOT NULL',
})
@Index('idx_api_keys_user', ['userId'])
@Index('idx_api_keys_tenant', ['tenantId'])
export class ApiKey {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ type: 'uuid', nullable: false, name: 'tenant_id' })
  tenantId: string;

  // Descripción
  @Column({ type: 'varchar', length: 255, nullable: false })
  name: string;

  // Seguridad
  @Column({ type: 'varchar', length: 16, nullable: false, name: 'key_index' })
  keyIndex: string;

  @Column({ type: 'varchar', length: 255, nullable: false, name: 'key_hash' })
  keyHash: string;

  // Scope y restricciones
  @Column({ type: 'varchar', length: 100, nullable: true })
  scope: string | null;

  @Column({ type: 'inet', array: true, nullable: true, name: 'allowed_ips' })
  allowedIps: string[] | null;

  // Expiración
  @Column({
    type: 'timestamptz',
    nullable: true,
    name: 'expiration_date',
  })
  expirationDate: Date | null;

  @Column({ type: 'timestamptz', nullable: true, name: 'last_used_at' })
  lastUsedAt: Date | null;

  // Estado
  @Column({ type: 'boolean', default: true, nullable: false, name: 'is_active' })
  isActive: boolean;

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

  @ManyToOne(() => Tenant, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant;

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

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

  @Column({ type: 'timestamptz', nullable: true, name: 'revoked_at' })
  revokedAt: Date | null;

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