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

export enum AiProvider {
  OPENAI = 'OPENAI',
  DEEPSEEK = 'DEEPSEEK',
  OPENAI_COMPATIBLE = 'OPENAI_COMPATIBLE',
}

export const SINGLETON_KEY = 'GLOBAL';

@Entity('ai_config')
@Index('uq_ai_config_singleton', ['singletonKey'], { unique: true })
export class AiConfig {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'singleton_key', type: 'varchar', length: 20, default: SINGLETON_KEY })
  singletonKey: string;

  @Column({ type: 'varchar', length: 50, default: AiProvider.OPENAI })
  provider: AiProvider;

  @Column({ name: 'base_url', type: 'varchar', length: 500, nullable: true })
  baseUrl: string;

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

  @Column({ name: 'api_key_iv', type: 'varchar', length: 50, nullable: true })
  apiKeyIv: string | null;

  @Column({ name: 'api_key_auth_tag', type: 'varchar', length: 50, nullable: true })
  apiKeyAuthTag: string | null;

  @Column({ name: 'key_last4', type: 'varchar', length: 4, nullable: true })
  keyLast4: string | null;

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

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

  @Column({ name: 'timeout_ms', type: 'int', default: 30000 })
  timeoutMs: number;

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

  @Column({ name: 'last_tested_at', type: 'datetime', nullable: true })
  lastTestedAt: Date | null;

  @Column({ name: 'last_test_latency_ms', type: 'int', nullable: true })
  lastTestLatencyMs: number | null;

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

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date;
}
