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

/**
 * PAC environment type aligned with DDL fiscal.cfdi_pac_configurations.environment
 */
export type PacEnvironment = 'sandbox' | 'production';

/**
 * CFDI PAC Configuration Entity
 * Aligned with DDL: fiscal.cfdi_pac_configurations (27-cfdi-core.sql)
 *
 * Stores connection configuration for Proveedores Autorizados de Certificacion (PAC)
 * used for CFDI stamping (timbrado).
 */
@Entity({ schema: 'fiscal', name: 'cfdi_pac_configurations' })
@Unique(['tenantId', 'pacCode'])
@Index('idx_cfdi_pac_tenant', ['tenantId'])
@Index('idx_cfdi_pac_code', ['pacCode'])
export class CfdiPacConfiguration {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  // PAC identification
  @Column({ type: 'varchar', length: 20, nullable: false, name: 'pac_code' })
  pacCode: string;

  @Column({ type: 'varchar', length: 100, nullable: false, name: 'pac_name' })
  pacName: string;

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

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

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

  // Endpoints
  @Column({ type: 'varchar', length: 500, nullable: true, name: 'production_url' })
  productionUrl: string | null;

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

  // Configuration
  @Column({ type: 'varchar', length: 20, default: 'sandbox', name: 'environment' })
  environment: PacEnvironment;

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

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

  // Contract
  @Column({ type: 'varchar', length: 50, nullable: true, name: 'contract_number' })
  contractNumber: string | null;

  @Column({ type: 'date', nullable: true, name: 'contract_expires_at' })
  contractExpiresAt: Date | null;

  // Limits
  @Column({ type: 'integer', nullable: true, name: 'monthly_stamp_limit' })
  monthlyStampLimit: number | null;

  @Column({ type: 'integer', default: 0, name: 'stamps_used_this_month' })
  stampsUsedThisMonth: number;

  // 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;

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