import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { WhatsAppAccount } from './account.entity';
import { WhatsAppContact } from './contact.entity';

export type WAConversationStatus = 'open' | 'pending' | 'resolved' | 'closed';
export type WAConversationPriority = 'low' | 'normal' | 'high' | 'urgent';

@Entity({ name: 'conversations', schema: 'whatsapp' })
export class WhatsAppConversation {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Index()
  @Column({ name: 'account_id', type: 'uuid' })
  accountId: string;

  @Index()
  @Column({ name: 'contact_id', type: 'uuid' })
  contactId: string;

  @Index()
  @Column({ name: 'status', type: 'varchar', length: 20, default: 'open' })
  status: WAConversationStatus;

  @Column({ name: 'priority', type: 'varchar', length: 20, default: 'normal' })
  priority: WAConversationPriority;

  @Index()
  @Column({ name: 'assigned_to', type: 'uuid', nullable: true })
  assignedTo: string;

  @Column({ name: 'assigned_at', type: 'timestamptz', nullable: true })
  assignedAt: Date;

  @Column({ name: 'team_id', type: 'uuid', nullable: true })
  teamId: string;

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

  @Column({ name: 'tags', type: 'text', array: true, default: [] })
  tags: string[];

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

  @Column({ name: 'context_id', type: 'uuid', nullable: true })
  contextId: string;

  @Column({ name: 'first_response_at', type: 'timestamptz', nullable: true })
  firstResponseAt: Date;

  @Column({ name: 'resolved_at', type: 'timestamptz', nullable: true })
  resolvedAt: Date;

  @Column({ name: 'message_count', type: 'int', default: 0 })
  messageCount: number;

  @Column({ name: 'unread_count', type: 'int', default: 0 })
  unreadCount: number;

  @Column({ name: 'metadata', type: 'jsonb', default: {} })
  metadata: Record<string, any>;

  @Index()
  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt: Date;

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

  @ManyToOne(() => WhatsAppAccount, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'account_id' })
  account: WhatsAppAccount;

  @ManyToOne(() => WhatsAppContact, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'contact_id' })
  contact: WhatsAppContact;
}
