import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  ManyToOne,
  JoinColumn,
  ManyToMany,
  JoinTable,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  OneToMany,
} from 'typeorm';
import { Country } from '../../countries/entities/country.entity';
import { Standard } from '../../standards/entities/standard.entity';
import { CompanyBranch } from './company-branch.entity';
import { CompanyClientLink } from './company-client-link.entity';

@Entity({ name: 'companies' })
@Index('idx_company_code', ['company_code'], { unique: true })
@Index('idx_company_name', ['name'], { unique: true })
export class Company {
  @PrimaryGeneratedColumn()
  id: number;

  // 🔧 FIX: length was 20, DB is varchar(50) — generated codes like "SOL-2026-06-000042" can exceed 20
  @Column({ type: 'varchar', unique: true, length: 50 })
  company_code: string;

  @Column({ type: 'varchar', unique: true, length: 255 })
  name: string;

  @Column({ type: 'varchar', unique: true, length: 255, nullable: true })
  @Index('idx_company_normalized_name', { unique: true })
  normalized_name: string;

  @OneToMany(() => CompanyBranch, (b) => b.company)
  branches: CompanyBranch[];

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

  @OneToMany(() => CompanyClientLink, (l) => l.company)
  clientLinks: CompanyClientLink[];

  @Column({ type: 'text', nullable: true })
  address: string;

  @Column({ type: 'varchar', length: 100, nullable: true })
  city: string;

  @Column({ type: 'varchar', length: 100, nullable: true })
  contact_person: string;

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

  @Column({ type: 'varchar', length: 150, nullable: true })
  email: string;

  // 🔧 FIX: length was 20, DB is varchar(50) — formatted numbers like "+971 50 261 3961" need more room
  @Column({ type: 'varchar', length: 50 })
  mobile: string;

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

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

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

  @Column({ type: 'varchar', length: 50, nullable: true })
  validity: string;

  @Column({ type: 'varchar', length: 100, nullable: true })
  certification_body: string;

  @Column({ type: 'varchar', length: 50, nullable: true })
  client_group: string;

  @Column({ type: 'varchar', length: 100, nullable: true })
  accreditation: string;

  @Column({ type: 'text' })
  scope_of_work: string;

  // ✅ Uploaded Documents (PDF / Word)
  @Column('json', { nullable: true })
  documents?: {
    originalName: string;
    fileName: string;
    filePath: string;
  }[];

  // ═══════════════════════════════════════════════════════════════════════
  // 🆕 ISSUE 1 FIX — 5 columns that exist in the DB but were missing
  //    from the entity. Without these, TypeORM can silently NULL them
  //    out on any repo.save() call.
  // ═══════════════════════════════════════════════════════════════════════

  // Which user (marketing) created this company record
  @Column({ type: 'int', nullable: true, comment: 'User who added this company (marketing owner)' })
  created_by_id: number | null;

  @Column({
    type: 'enum',
    enum: ['QRS', 'TQS'],
    default: 'QRS',
  })
  scheme: 'QRS' | 'TQS';
  // Which old CRM database this company was imported from
  @Column({ type: 'enum', enum: ['QRS', 'TQS'], nullable: true })
  legacy_source: 'QRS' | 'TQS' | null;

  // The ID in the old CRM (e.g. client id 10505 from the QRS database)
  @Column({ type: 'int', nullable: true })
  legacy_ref_id: number | null;

  // Business lifecycle status of this client
  @Column({
    type: 'enum',
    enum: ['LEAD', 'PROSPECT', 'ACTIVE', 'INACTIVE'],
    default: 'PROSPECT',
  })
  client_status: 'LEAD' | 'PROSPECT' | 'ACTIVE' | 'INACTIVE';

  // NC stamp image data (used in NC reports)
  @Column({ type: 'mediumtext', nullable: true })
  nc_stamp_img: string | null;

  // ----------------- Relations -----------------
  @ManyToOne(() => Country)
  @JoinColumn({ name: 'country_id' })
  country: Country;

  @ManyToMany(() => Standard)
  @JoinTable({
    name: 'company_standards',
    joinColumn: { name: 'company_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'standard_id', referencedColumnName: 'id' },
  })
  standards: Standard[];

  // ----------------- Timestamps -----------------
  @CreateDateColumn({ type: 'timestamp' })
  created_at: Date;

  @UpdateDateColumn({ type: 'timestamp' })
  updated_at: Date;
}
