// ═══════════════════════════════════════════════════════════════
//  lib/api/types/checklist.types.ts
// ═══════════════════════════════════════════════════════════════

export interface Standard {
  id: number;
  name: string;
  title?: string;
}

export interface ChecklistTemplateItem {
  id: number;
  item_text: string;
  category?: string | null;
  sort_order: number;
}

export interface ChecklistTemplate {
  id: number;
  name: string;
  is_generic: boolean;
  standard_id: number | null;
  standard?: Standard | null;
  items: ChecklistTemplateItem[];
  /** Who generated this template. Null on rows created before this field existed. */
  created_by?: number | null;
  created_by_user?: { id?: number; firstName?: string; lastName?: string } | null;
}

export type ChecklistItemStatus = "missing" | "uploaded" | "approved" | "rejected";

export interface AuditChecklistItem {
  id: number;
  status: ChecklistItemStatus;
  document_path?: string | null;
  document_original_name?: string | null;
  uploaded_by_user?: { firstName?: string; lastName?: string } | null;
  uploaded_at?: string | null;
  reviewed_at?: string | null;
  rejection_note?: string | null;
  template_item: { item_text: string };
}

export interface BuildChecklistDto {
  standard_id: number;
  template_item_ids: number[];
}

export interface CreateTemplateDto {
  name: string;
  is_generic: boolean;
  standard_id: number | null;
  items: { item_text: string; sort_order: number }[];
}

export interface UpdateTemplateDto {
  name: string;
  is_generic: boolean;
  standard_id: number | null;
  items: { id?: number; item_text: string; sort_order: number }[];
}

export interface ReviewItemDto {
  decision: "approve" | "reject";
  note?: string;
}

// ═══════════════════════════════════════════════════════════════
// Client-portal workflow additions (build → review → notify →
// client uploads → auditor review). Everything below is additive -
// nothing above changed shape.
// ═══════════════════════════════════════════════════════════════

export type AuditChecklistStatus = "draft" | "submitted";

export interface UserNameRef {
  id?: number;
  firstName?: string;
  lastName?: string;
  email?: string;
}

/** Item as returned by GET audits/:rowId/checklists (grouped read). */
export interface AuditChecklistItemFull extends AuditChecklistItem {
  reviewed_by_user?: UserNameRef | null;
}

/** One checklist = one standard on one audit, with lifecycle stamps. */
export interface AuditChecklistFull {
  id: number;
  audit_schedule_row_id: number;
  company_id: number;
  standard_id: number;
  standard?: Standard | null;
  company?: { id: number; name: string; email?: string | null } | null;
  status: AuditChecklistStatus;
  submitted_at?: string | null;
  submitted_by_user?: UserNameRef | null;
  client_notified_at?: string | null;
  client_submitted_at?: string | null;
  completed_at?: string | null;
  /** JSON array string of the emails confirmed at notify time */
  notify_emails?: string | null;
  client_message?: string | null;
  due_date?: string | null;
  items: AuditChecklistItemFull[];
  created_at?: string;
  updated_at?: string;
}

export interface NotifyClientDto {
  emails: string[];
  message?: string | null;
  due_date?: string | null; // YYYY-MM-DD
}

/** Where one checklist sits in the approved 9-step flow. */
export type ChecklistStage =
  | "none"          // no checklist for this standard yet → build
  | "review"        // draft built → auditor reviews the PDF & confirms
  | "notify"        // confirmed → auditor sends to client (multi-email)
  | "with_client"   // notified → waiting on client uploads
  | "client_submitted" // client pressed Submit → review the documents
  | "completed";    // every item approved

export function checklistStage(c: AuditChecklistFull | null | undefined): ChecklistStage {
  if (!c) return "none";
  if (c.completed_at) return "completed";
  if (c.client_submitted_at) return "client_submitted";
  if (c.client_notified_at) return "with_client";
  if (c.status === "submitted") return "notify";
  return "review";
}

export function parseNotifyEmails(raw: string | null | undefined): string[] {
  if (!raw) return [];
  try {
    const arr = JSON.parse(raw);
    return Array.isArray(arr) ? arr.filter((e) => typeof e === "string") : [];
  } catch {
    return raw.split(",").map((e) => e.trim()).filter(Boolean);
  }
}