// ─── Enums ─────────────────────────────────────────────────────────────────
export type AuditRequestStatus =
  | "DRAFT"
  | "SUBMITTED"
  | "UNDER_REVIEW"
  | "SCHEDULED"
  | "REJECTED"
  | "CANCELLED"
  | "COMPLETED";

export type AuditMode = "ONLINE" | "ONSITE" | "HYBRID";

export type CertificationType =
  | "INITIAL"
  | "SURVEILLANCE"        // 🆕 add this
  | "SURVEILLANCE_1"
  | "SURVEILLANCE_2"
  | "RECERTIFICATION"
  | "SURVEILLANCE_RECERT"
  | "Recertification or renewal";

// Reuses the same audit_type and audit_mode enums from audit-schedules
// for the coordinator's schedule action (which creates an audit_schedule_row)
export type ScheduleAuditType =
  | "INITIAL"
  | "SURVEILLANCE"
  | "RECERTIFICATION";
export type ClientGroup = "QRS" | "TQS" | "QRS_B";
export interface Auditee {
  name: string;
  designation: string;
}
export type ScheduleAuditMode = "ONSITE" | "OFFICE";

// ─── Related entities (slim) ───────────────────────────────────────────────
export interface MiniUser {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
}

export interface MiniCompany {
  id: number;
  name: string;
  company_code?: string;
  address?: string;
  city?: string;
  email?: string;
}

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

// Slim audit_schedule_row reference (only fields we need from the link)
export interface MiniAuditScheduleRow {
  id: number;
  audit_code: string;
  schedule_id: number;
  audit_type: ScheduleAuditType;
  audit_stage?: string | null;
  audit_mode: ScheduleAuditMode;
  audit_time?: string | null;
  audit_time_label?: string | null;
  status: string;
  lead_auditor_id: number;
  lead_auditor?: MiniUser;
  schedule?: {
    id: number;
    schedule_date: string;
    title: string;
    status: string;
  };
}

// ─── Main entity ───────────────────────────────────────────────────────────
export interface AuditRequest {
  id: number;

  // Client + auditee (from marketing form)
  company_id: number | null;
  company?: MiniCompany | null;
  company_name?: string | null;
  company_source?: string | null;
  client_group?: ClientGroup;   // 🆕
  client_ref_id?: number | null;
  // company?: MiniCompany;
  auditee_name: string;
  auditee_contact: string;
  auditee_email: string;
  auditees?: Auditee[] | null;   // 🆕

  // Audit scope
  standard_ids: number[];
  certification_type: CertificationType;
  accreditation: string;

  // 🆕 Certification details — carried into the inquiry on Proceed
  scope_of_work?: string | null;
  previous_cert_no?: string | null;

  // Scheduling preference (marketing's proposal)
  proposed_date: string;       // YYYY-MM-DD
  proposed_time: string;       // HH:mm:ss
  location: string;
  mode: AuditMode;
  marketing_remarks?: string | null;

  // Coordinator-set fields
  coordinator_remarks?: string | null;
  status: AuditRequestStatus;

  reviewed_by_id?: number | null;
  reviewed_by?: MiniUser | null;
  reviewed_at?: string | null;
  scheduled_at?: string | null;
  rejection_reason?: string | null;

  // Link to the actual scheduled audit row (once scheduled)
  audit_schedule_row_id?: number | null;
  audit_schedule_row?: MiniAuditScheduleRow | null;

  // 🆕 Link to the inquiry created via "Proceed to Inquiry" (null until used)
  inquiry_id?: number | null;

  // Uploaded documents (JSON column) — doc_type added for typed uploads
  documents?: {
    doc_type?: string;
    filename: string;
    path: string;
    mimetype: string;
    size: number;
  }[] | null;

  // Audit trail
  requested_by_id: number;
  requested_by?: MiniUser;

  created_at: string;
  updated_at: string;
}

// ─── DTOs ──────────────────────────────────────────────────────────────────

export interface CreateAuditRequestDto {
  company_id?: number;
  company_name: string;
  company_source?: string;
  client_group: ClientGroup;   // 🆕
  client_ref_id?: number;
  auditee_name: string;
  auditee_contact: string;
  auditee_email: string;
  auditees?: Auditee[];   // 🆕
  standard_ids: number[];
  certification_type: CertificationType;
  accreditation: string;
  scope_of_work?: string;        // 🆕
  previous_cert_no?: string;     // 🆕
  proposed_date: string;
  proposed_time: string;
  location: string;
  mode: AuditMode;
  marketing_remarks?: string
}

export interface UpdateAuditRequestDto {
  status?: AuditRequestStatus;   // 🆕 coordinator/admin-only
  client_group?: ClientGroup;   // 🆕
  auditee_name?: string;
  auditee_contact?: string;
  auditee_email?: string;
  auditees?: Auditee[];   // 🆕  ← ADD THIS LINE
  standard_ids?: number[];
  certification_type?: CertificationType;
  accreditation?: string;
  scope_of_work?: string;        // 🆕
  previous_cert_no?: string;     // 🆕
  proposed_date?: string;
  proposed_time?: string;
  location?: string;
  mode?: AuditMode;
  marketing_remarks?: string;
}

// Coordinator schedules the request → creates audit_schedule_row
export interface ScheduleAuditRequestDto {
  lead_auditor_id: number;
  co_auditor_ids?: number[];   // 🆕
  audit_date: string;          // YYYY-MM-DD (may differ from proposed_date)
  audit_time: string;          // HH:mm
  audit_time_label: string;    // e.g. "11.00AM"
  audit_type: ScheduleAuditType;
  audit_stage?: string;
  audit_mode?: ScheduleAuditMode;
  client_group?: string;
  coordinator_remarks?: string;
  notes?: string;
}

export interface RejectAuditRequestDto {
  rejection_reason: string;
}

export interface CancelAuditRequestDto {
  cancellation_reason: string;
  cancellation_notes?: string;
}

// ─── Query params ──────────────────────────────────────────────────────────
export interface AuditRequestQueryParams {
  page?: number;
  limit?: number;
  status?: AuditRequestStatus;
  company_id?: number;
  requested_by_id?: number;
  date_from?: string;
  date_to?: string;
  search?: string;
}

// ─── Responses ─────────────────────────────────────────────────────────────
export interface PaginatedAuditRequestsResponse {
  data: AuditRequest[];
  total: number;
  page: number;
  lastPage: number;
  limit?: number;
}

export interface AuditRequestAnalytics {
  submitted: number;
  under_review: number;
  scheduled: number;
  completed: number;
  rejected: number;
  cancelled: number;
  total: number;
}
// ═══════════════════════════════════════════════════════════════════════
// ADD THESE to src/lib/api/types/audit-request.types.ts
// (additive — nothing existing changes)
// ═══════════════════════════════════════════════════════════════════════

// One client inside a batch. Mirrors BatchClientDto on the backend.
export interface BatchClientPayload {
  company_id?: number;
  company_name: string;
  company_source?: string;
  client_ref_id?: number;

  auditee_name: string;
  auditee_contact: string;
  auditee_email: string;
  auditees?: { name: string; designation?: string; email?: string; contact?: string }[];

  standard_ids: number[];
  certification_type: CertificationType;
  mode: AuditMode;              // 🆕 ADD THIS LINE

  scope_of_work?: string;        // 🆕 per-client certification details
  previous_cert_no?: string;     // 🆕

  proposed_date: string;
  proposed_time: string;
  location: string;

  marketing_remarks?: string;
}

// The batch request body. Shared group/accreditation/mode + clients[].
export interface CreateBatchAuditRequestPayload {
  client_group: ClientGroup;
  accreditation: string;
  marketing_remarks?: string;
  clients: BatchClientPayload[];
}

// What the backend returns from POST /audit-requests/batch
export interface CreateBatchAuditRequestResult {
  ok: true;
  count: number;
  created: Array<{
    index: number;
    id: number;
    company_name: string;
  }>;
}
// ─── Table row shape (flat, like AuditScheduleRow) ─────────────────────────
export interface AuditRequestTableRow {
  sno: number;
  id: number;
  status: AuditRequestStatus;
  company_id: number | null;
  company_name: string;
  auditee_name: string;
  auditee_email: string;
  certification_type: CertificationType;
  proposed_date: string;
  proposed_time: string;
  location: string;
  mode: AuditMode;
  requested_by_name: string;
  requested_by_email: string;
  reviewed_by_name: string;
  audit_code: string;          // from linked audit_schedule_row, or "—"
  audit_schedule_row_id: number | null;
  // ✅ NEW — lead auditor name from the linked audit_schedule_row.
  // "N/A" until the request is scheduled (no linked row yet).
  lead_auditor_name: string;
  // 🆕 Proceed to Inquiry — link + carried fields
  inquiry_id: number | null;
  scope_of_work: string;
  previous_cert_no: string;
  created_at: string;
  // raw object for modal access
  raw: AuditRequest;
  [key: string]: any;
}
// ═══════════════════════════════════════════════════════════════════════
// 🆕 PROCEED TO INQUIRY — types (mirror ProceedToInquiryDto on the backend)
// ═══════════════════════════════════════════════════════════════════════

// Every field optional — anything omitted falls back server-side to the
// value stored on the audit request itself.
export interface ProceedToInquiryPayload {
  inquiry_type?: string;          // 'INITIAL' | 'SURVEILLANCE' | 'RE_CERTIFICATION'
  audit_date?: string;            // YYYY-MM-DD
  auditor_name?: string;
  cert_body?: string;             // 'QRS' | 'TQS'
  audit_stage?: string;           // 'Stage 1' | 'Stage 2' | 'Surveillance' | 'Recertification'
  previous_cert_no?: string;
  scope_of_work?: string;         // edits here also sync to companies.scope_of_work
  notes?: string;
  surveillance_audit_due?: string;
  recertification_due?: string;
  standards?: number[];
  assigned_to_id?: number;
}

export interface ProceedBatchToInquiryPayload {
  request_ids: number[];
  overrides?: ProceedToInquiryPayload;
}

// Slim inquiry shape returned by the proceed endpoints
export interface ProceedInquiryResult {
  id: number;
  inquiry_ref: string;
  inquiry_type: string;
  audit_date: string;
  auditor_name: string;
  status: string;
  [key: string]: any;
}

export interface ProceedToInquiryResult {
  request: AuditRequest;
  inquiry: ProceedInquiryResult;
}

// 🆕 ─── Slot system types ──────────────────────────────────────────────────
export interface SlotDate {
  date: string;
  booked: number;
  available: number;
  status: 'open' | 'full';
}

export interface AvailableSlotsResponse {
  window_start: string;
  window_end: string;
  max_per_day: number;
  dates: SlotDate[];
}

export interface ProceedBatchToInquiryResult {
  ok: true;
  results: Array<
    | { id: number; ok: true; inquiry_id: number; inquiry_ref: string }
    | { id: number; ok: false; error: string }
  >;
}