import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
} from 'typeorm';

/**
 * Certificate status aligned with DDL fiscal.cfdi_certificate_status
 */
export enum CertificateStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive',
  EXPIRED = 'expired',
  REVOKED = 'revoked',
  PENDING = 'pending',
}

/**
 * CFDI Certificate Entity
 * Aligned with DDL: fiscal.cfdi_certificates
 */
@Entity({ schema: 'fiscal', name: 'cfdi_certificates' })
@Index('idx_cfdi_certificates_tenant', ['tenantId'])
@Index('idx_cfdi_certificates_rfc', ['rfc'])
@Index('idx_cfdi_certificates_status', ['status'])
@Index('idx_cfdi_certificates_expires', ['expiresAt'])
@Index('idx_cfdi_certificates_default', ['isDefault'])
export class CfdiCertificate {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ type: 'varchar', length: 13, nullable: false })
  rfc: string;

  @Column({ type: 'varchar', length: 20, nullable: false, name: 'certificate_number' })
  certificateNumber: string;

  @Column({ type: 'varchar', length: 100, nullable: false, unique: true, name: 'serial_number' })
  serialNumber: string;

  @Column({ type: 'text', nullable: false, name: 'certificate_pem' })
  certificatePem: string;

  @Column({ type: 'text', nullable: false, name: 'private_key_pem_encrypted' })
  privateKeyPemEncrypted: string;

  @Column({ type: 'timestamptz', nullable: false, name: 'issued_at' })
  issuedAt: Date;

  @Column({ type: 'timestamptz', nullable: false, name: 'expires_at' })
  expiresAt: Date;

  @Column({
    type: 'enum',
    enum: CertificateStatus,
    default: CertificateStatus.PENDING,
    nullable: false,
  })
  status: CertificateStatus;

  @Column({ type: 'varchar', length: 500, nullable: true, name: 'issuer_name' })
  issuerName: string | null;

  @Column({ type: 'varchar', length: 500, nullable: true, name: 'subject_name' })
  subjectName: string | null;

  @Column({ type: 'varchar', length: 255, nullable: true, name: 'description' })
  description: string | null;

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

  @Column({ type: 'boolean', default: false, nullable: false, name: 'is_default' })
  isDefault: boolean;

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

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

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz', nullable: true })
  updatedAt: Date | null;

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

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

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