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

import { Company } from '../../companies/entities/company.entity';
import { User } from '../../user/entities/user.entity';
import { AuditScheduleRow } from '../../audit-schedules/entities/audit-schedule-row.entity';
import { CompanyBranch } from '../../companies/entities/company-branch.entity';
// ─── ENUMS ───────────────────────────────────────────────────────────────

export enum AuditRequestStatus {
  DRAFT = 'DRAFT',
  SUBMITTED = 'SUBMITTED',
  UNDER_REVIEW = 'UNDER_REVIEW',
  SCHEDULED = 'SCHEDULED',
  REJECTED = 'REJECTED',
  CANCELLED = 'CANCELLED',
  COMPLETED = 'COMPLETED',
}
export enum ClientGroup {
  QRS = 'QRS',
  TQS = 'TQS',
  QRS_B = 'QRS_B',
}
export enum AuditMode {
  ONLINE = 'ONLINE',
  ONSITE = 'ONSITE',
  HYBRID = 'HYBRID',
}

export enum CertificationType {
  INITIAL = 'INITIAL', // First-time certification
  SURVEILLANCE = 'SURVEILLANCE', // First-time certification
  SURVEILLANCE_1 = 'SURVEILLANCE_1',
  SURVEILLANCE_2 = 'SURVEILLANCE_2',
  RECERTIFICATION = 'RECERTIFICATION',
  SURVEILLANCE_RECERT = 'SURVEILLANCE_RECERT',
  RECERTIFICATION_OR_RENEWAL = 'Recertification or renewal',
}

// ─── ENTITY ──────────────────────────────────────────────────────────────

@Entity('audit_requests')
@Index(['status'])
@Index(['company_id'])
@Index(['requested_by_id'])
@Index(['proposed_date'])
export class AuditRequest {
  @PrimaryGeneratedColumn({ type: 'int' })
  id: number;

  // ─── Client & auditee (from marketing form) ──────────────────────────
  @Column({ type: 'int', nullable: true })
  company_id: number | null;

  @ManyToOne(() => Company, { nullable: true })
  @JoinColumn({ name: 'company_id' })
  company: Company | null;

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

  @Column({ type: 'varchar', length: 20, nullable: true })
  company_source: string | null; // 'Client' | 'Surveillance'

  @Column({ type: 'enum', enum: ClientGroup, default: ClientGroup.QRS })
  client_group: ClientGroup;

  @Column({ type: 'int', nullable: true })
  client_ref_id: number | null; // the id from the clients DB (e.g. 10505)
  @Column({ type: 'varchar', length: 150 })
  auditee_name: string;

  @Column({ type: 'varchar', length: 30 })
  auditee_contact: string;

  @Column({ type: 'varchar', length: 150 })
  auditee_email: string;

  @Column({ type: 'json', nullable: true })
  auditees: { name: string; designation: string }[] | null;

  // ─── Audit scope (from marketing form) ───────────────────────────────
  // Array of standard IDs stored as JSON for simplicity.
  @Column({ type: 'json' })
  standard_ids: number[];

  @Column({
    type: 'enum',
    enum: CertificationType,
  })
  certification_type: CertificationType;

  @Column({ type: 'varchar', length: 50 })
  accreditation: string;

  // 🆕 ─── Certification details (from marketing form) ───────────────────
  // Captured at submit time — flows into the inquiry on Proceed to Inquiry
  // and is synced to companies.scope_of_work.
  @Column({ type: 'text', nullable: true })
  scope_of_work: string | null;

  @Column({ type: 'varchar', length: 120, nullable: true })
  previous_cert_no: string | null;

  // ─── Scheduling preference (from marketing form) ─────────────────────
  @Column({ type: 'date' })
  proposed_date: string;

  @Column({ type: 'time' })
  proposed_time: string;

  @Column({ type: 'varchar', length: 255 })
  location: string;

  @Column({ type: 'enum', enum: AuditMode })
  mode: AuditMode;

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

  // ─── Coordinator-set fields ──────────────────────────────────────────
  @Column({ type: 'text', nullable: true })
  coordinator_remarks: string | null;

  @Column({
    type: 'enum',
    enum: AuditRequestStatus,
    default: AuditRequestStatus.SUBMITTED,
  })
  status: AuditRequestStatus;

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

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

  @Column({ type: 'timestamp', nullable: true })
  reviewed_at: Date | null;

  @Column({ type: 'timestamp', nullable: true })
  scheduled_at: Date | null;

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

  // ─── FK link to the actual scheduled audit row ───────────────────────
  // Null until coordinator schedules. Once set, marks status = SCHEDULED.
  @Column({ type: 'int', nullable: true })
  audit_schedule_row_id: number | null;

  @OneToOne(() => AuditScheduleRow, { nullable: true })
  @JoinColumn({ name: 'audit_schedule_row_id' })
  audit_schedule_row: AuditScheduleRow | null;

  // 🆕 ─── Link to the inquiry created from this request ─────────────────
  // Null until "Proceed to Inquiry" is used. Prevents proceeding twice and
  // lets the UI show the INQ-… badge on the row.
  @Column({ type: 'int', nullable: true })
  inquiry_id: number | null;

  // ─── Audit trail ─────────────────────────────────────────────────────
  @Column({ type: 'int' })
  requested_by_id: number;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'requested_by_id' })
  requested_by: User;
  // After existing company relation, ADD:

  @Column({ type: 'int', nullable: true, name: 'company_branch_id' })
  company_branch_id: number | null;  // ✅ CORRECT naming

  @ManyToOne(() => CompanyBranch, (b) => b.auditRequests, { nullable: true })
  @JoinColumn({ name: 'company_branch_id' })
  branch: CompanyBranch | null;
  // @Column({ type: 'json', nullable: true })
  // documents: { filename: string; path: string; mimetype: string; size: number }[] | null;

  @Column({ type: 'json', nullable: true })
  documents: { doc_type?: string; filename: string; path: string; mimetype: string; size: number }[] | null;

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

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