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

export type ConversationStatus = 'active' | 'waiting' | 'resolved' | 'blocked';
export type MessageDirection = 'inbound' | 'outbound';

@Entity({ name: 'contacts', schema: 'whatsapp' })
@Unique(['accountId', 'phoneNumber'])
export class WhatsAppContact {
  @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: 'phone_number', type: 'varchar', length: 20 })
  phoneNumber: string;

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

  @Column({ name: 'profile_name', type: 'varchar', length: 200, nullable: true })
  profileName: string;

  @Column({ name: 'profile_picture_url', type: 'text', nullable: true })
  profilePictureUrl: string;

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

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

  @Column({ name: 'conversation_status', type: 'varchar', length: 20, default: 'active' })
  conversationStatus: ConversationStatus;

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

  @Column({ name: 'last_message_direction', type: 'varchar', length: 10, nullable: true })
  lastMessageDirection: MessageDirection;

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

  @Column({ name: 'can_send_template_only', type: 'boolean', default: true })
  canSendTemplateOnly: boolean;

  @Index()
  @Column({ name: 'opted_in', type: 'boolean', default: false })
  optedIn: boolean;

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

  @Column({ name: 'opted_out', type: 'boolean', default: false })
  optedOut: boolean;

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

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

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

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

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

  @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;
}
