import { BaseEntity } from "@edr/api-common";
import { SupportAuthorRole } from "@edr/types";
import { Column, Entity, Index } from "typeorm";

/**
 * The single support thread for a customer **company**. Any portal user of that
 * company sees and continues it; backoffice agents work a shared inbox. Either
 * side may open it — whoever sends the first message — and it has no lifecycle:
 * no status, no resolve, no close.
 *
 * The unique index on `company_id` is what enforces one-thread-per-company; the
 * get-or-create path relies on it to settle races. Last-message fields are
 * denormalized so the inbox list can sort and preview without joining
 * `support_messages`. Read cursors are per-side (shared across a company's
 * users) — unread = messages from the other role newer than the side's cursor.
 */
@Entity({ schema: "freight", name: "support_conversations" })
@Index("IDX_SUPPORT_CONV_COMPANY", ["companyId"], {
  unique: true,
  where: "deleted_at IS NULL",
})
@Index("IDX_SUPPORT_CONV_LASTMSG", ["lastMessageAt"])
export class SupportConversation extends BaseEntity {
  @Column({ name: "company_id", type: "uuid" })
  companyId!: string;

  /** Denormalized company name for the agent inbox (resolved at creation). */
  @Column({ name: "company_name", type: "varchar", length: 200, nullable: true })
  companyName?: string | null;

  /** Null when an agent opened the thread — no customer created it. */
  @Column({ name: "created_by_user_id", type: "uuid", nullable: true })
  createdByUserId?: string | null;

  @Column({ name: "last_message_at", type: "timestamptz", nullable: true })
  lastMessageAt?: Date | null;

  @Column({ name: "last_message_preview", type: "varchar", length: 280, nullable: true })
  lastMessagePreview?: string | null;

  @Column({
    name: "last_message_author_role",
    type: "varchar",
    length: 12,
    nullable: true,
  })
  lastMessageAuthorRole?: SupportAuthorRole | null;

  @Column({ name: "customer_last_read_at", type: "timestamptz", nullable: true })
  customerLastReadAt?: Date | null;

  @Column({ name: "agent_last_read_at", type: "timestamptz", nullable: true })
  agentLastReadAt?: Date | null;
}
