import { Entity, Column, Unique, ManyToOne, OneToMany, JoinColumn } from 'typeorm';
import { BaseEntity } from '../database/base.entity';
import { DestinationEntity } from './destination.entity';
import { TripSourceEntity } from './trip-source.entity';
import { CurrencyEntity } from './currency.entity';
import { QueryQuoteEntity } from './query-quote.entity';

export enum QueryStage {
  NEW = 'new',
  IN_PROGRESS = 'in_progress',
  CONVERTED = 'converted',
  ON_HOLD = 'on_hold',
  ON_TRIP = 'on_trip',
  PAST_TRIP = 'past_trip',
  CANCELLED = 'cancelled',
  DROPPED = 'dropped',
}

/**
 * Query entity — tenant-scoped.
 *
 * Represents a customer inquiry/trip request.
 * Flows through stages: New → In Progress → On Trip → Past Trip (or Cancelled/Dropped).
 * Links to Destination, Trip Source, and assigned team member.
 */
@Entity('queries')
@Unique(['tenant_id', 'query_number'])
export class QueryEntity extends BaseEntity {
  // --- Auto-generated ---
  @Column({ type: 'varchar', length: 20 })
  query_number: string;

  // --- Source & Assignment ---
  @ManyToOne(() => TripSourceEntity)
  @JoinColumn({ name: 'source_id' })
  source: TripSourceEntity;

  @Column({ type: 'uuid' })
  source_id: string;

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

  @Column({ type: 'jsonb', default: [] })
  sales_team: string[];

  @Column({ type: 'jsonb', nullable: true })
  source_tags: string[] | null;

  @Column({ type: 'jsonb', nullable: true })
  remark_tags: string[] | null;

  // --- Trip Details ---
  @ManyToOne(() => DestinationEntity)
  @JoinColumn({ name: 'destination_id' })
  destination: DestinationEntity;

  @Column({ type: 'uuid' })
  destination_id: string;

  @Column({ type: 'date' })
  start_date: string;

  @Column({ type: 'date' })
  end_date: string;

  @Column({ type: 'int' })
  adults: number;

  @Column({ type: 'simple-json', nullable: true })
  children_ages: number[] | null;

  @Column({ type: 'int', default: 0 })
  infants: number;

  // --- Guest Information ---
  @Column({ type: 'varchar', length: 255 })
  guest_name: string;

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

  @Column({ type: 'varchar', length: 20 })
  guest_mobile: string;

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

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

  // --- Stage ---
  @Column({ type: 'varchar', length: 20, default: QueryStage.NEW })
  stage: QueryStage;

  // --- Currency (for quotes) ---
  @ManyToOne(() => CurrencyEntity, { nullable: true })
  @JoinColumn({ name: 'currency_id' })
  currency: CurrencyEntity | null;

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

  // --- Quotes ---
  @OneToMany(() => QueryQuoteEntity, (q) => q.query)
  quotes: QueryQuoteEntity[];
}
