// Contract types for V2 features beyond the core list objects (master plan Part G / document 02 schema).
import type {
  DateOnly,
  Id,
  Iso,
  KpiValue,
  Indicator,
  ReportType,
  StageKey,
  RoleCode,
  VerificationRun,
} from "./types";

export type KpiCardData = KpiValue & {
  denominatorLabel?: string;
  name: string;
  unit: Indicator["unit"];
  direction: Indicator["direction"];
  verified?: number;
  trend: { date: string; value: number }[];
  previous?: number;
};

export interface ImportIssue {
  field: string;
  code: string;
  message: string;
  severity: "error" | "warning";
}
export interface ImportRow {
  rowNo: number;
  status: "ok" | "error" | "warning" | "duplicate";
  values: Record<string, string>;
  issues: ImportIssue[];
  duplicates?: {
    traineeId: Id;
    code: string;
    name: string;
    provider: string;
    score: number;
    reasons: string[];
  }[];
  decision?: "import" | "skip";
  decisionNote?: string;
}
export interface ImportBatch {
  id: Id;
  kind: "trainees" | "attendance" | "outcomes" | "kobo_results" | "roster_check";
  mode: "import" | "check_only";
  status:
    | "uploaded"
    | "validating"
    | "ready"
    | "has_errors"
    | "committing"
    | "committed"
    | "discarded"
    | "failed";
  fileName: string;
  createdAt: Iso;
  createdBy: string;
  target: { providerId: Id; trainingId?: Id; siteId?: Id; classId?: Id; label: string };
  counts: {
    total: number;
    valid: number;
    error: number;
    warning: number;
    duplicate: number;
    skipped: number;
    created?: number;
  };
  capacity?: { registered: number; adding: number; max: number };
  headerIssues: string[];
}
export interface RosterChange {
  id: Id;
  type: "add" | "withdraw" | "transfer" | "update_identity" | "update_eligibility";
  status: "submitted" | "approved" | "applied" | "rejected" | "withdrawn";
  providerCode: string;
  classCode: string;
  traineeId?: Id;
  traineeName?: string;
  reason: string;
  before?: Record<string, string>;
  after?: Record<string, string>;
  requestedBy: string;
  requestedAt: Iso;
  decidedBy?: string;
  decisionNote?: string;
}
export interface DupSide {
  id: Id;
  code: string;
  firstName: string;
  fatherName: string;
  grandfatherName: string;
  sex: string;
  age: number;
  dob?: string;
  phone: string;
  provider: string;
  classCode: string;
  registeredAt: Iso;
  attendanceRate?: number;
}
export interface DuplicatePair {
  id: Id;
  score: number;
  risk: "high" | "medium";
  status: "pending" | "confirmed_duplicate" | "not_duplicate";
  crossProvider: boolean;
  reasons: string[];
  a: DupSide;
  b: DupSide;
  note?: string;
}
export interface Correction {
  id: Id;
  classId: Id;
  classCode: string;
  date: DateOnly;
  traineeId: Id;
  traineeName: string;
  from: "P" | "A" | "E";
  to: "P" | "A" | "E";
  reason: string;
  status: "requested" | "approved" | "rejected";
  requestedBy: string;
  requestedAt: Iso;
  decisionNote?: string;
}
export interface DropoutRow {
  traineeId: Id;
  code: string;
  name: string;
  providerCode: string;
  classId: Id;
  classCode: string;
  rateToDate?: number;
  maxReachable?: number;
  rateFinal?: number;
  atRisk: boolean;
  systemFinal: boolean;
  tpReported: boolean;
  missingInReport: boolean;
  reason?: string;
}
export interface OutcomeLine {
  traineeId: Id;
  code: string;
  name: string;
  value?: "yes" | "no";
  locked?: boolean;
  lockReason?: string;
  eventDate?: DateOnly;
  reason?: string;
  details?: Record<string, string>;
}
export interface OutcomeReport {
  id: Id;
  classId: Id;
  classCode: string;
  providerCode: string;
  trainingTitle: string;
  reportType: ReportType;
  stageKey?: StageKey;
  version: number;
  status: "draft" | "ready" | "accepted" | "returned" | "superseded" | "discarded";
  rowsTotal: number;
  yesCount: number;
  noCount: number;
  naCount: number;
  submittedAt?: Iso;
  submittedBy?: string;
  reviewNote?: string;
  reasonForChange?: string;
  needsApproval?: boolean;
  lines: OutcomeLine[];
  versions: { id: Id; version: number; status: string; submittedAt?: Iso }[];
}
export interface ReportDraftContext {
  cls: {
    id: Id;
    code: string;
    trainingTitle: string;
    locationName: string;
    effectiveEnd: DateOnly;
    providerCode: string;
  };
  reportType: ReportType;
  stageKey?: StageKey;
  gates: { label: string; ok: boolean; detail?: string }[];
  lines: OutcomeLine[];
  resubmission: boolean;
  verificationUsed: boolean;
}
export interface IndicatorDetail {
  indicator: Indicator & {
    operationalDefinition: string;
    dataSources: string;
    frequency: string;
    computation: string;
    disaggregations: string[];
    paymentLinkage?: string;
    version: number;
    effectiveFrom: DateOnly;
    numeratorMetric: string;
    denominatorMetric?: string;
    numeratorLabel: string;
    denominatorLabel?: string;
    comparator: ">=" | "<=";
  };
  rows: {
    providerId: Id;
    providerCode: string;
    providerName: string;
    value?: number;
    verified?: number;
    target?: number;
    targetSource: string;
    status: string;
    numerator?: number;
    denominator?: number;
    note?: string;
  }[];
  total: { value?: number; target?: number; status: string };
  trend: { date: string; value: number }[];
  versions: {
    version: number;
    status: string;
    effectiveFrom: DateOnly;
    changeNote: string;
    approvedBy?: string;
  }[];
  disaggregation: { dimension: string; items: { label: string; value?: number }[] }[];
}
export interface TargetHistory {
  indicatorCode: string;
  providerId?: Id;
  value: number;
  effectiveFrom: DateOnly;
  effectiveTo?: DateOnly;
  note?: string;
  setBy: string;
}
export interface EvidenceRules {
  types: string[];
  minFiles: number;
  checklist: { key: string; label: string }[];
}
export interface ObligationSubmission {
  id: Id;
  version: number;
  status: "submitted" | "approved" | "returned" | "superseded";
  submittedAt: Iso;
  submittedBy: string;
  isLate: boolean;
  files: { id: Id; name: string; sizeKb: number }[];
  checklist: Record<string, boolean>;
  note?: string;
  review?: {
    decidedBy: string;
    decidedAt: Iso;
    note?: string;
    items: Record<string, { ok: boolean; comment?: string }>;
  };
}
export interface ObligationDetail {
  id: Id;
  providerId: Id;
  providerCode: string;
  providerName: string;
  scopeLabel: string;
  openDate: DateOnly;
  dueDate: DateOnly;
  closeDate: DateOnly;
  status: string;
  activity: {
    code: string;
    name: string;
    scope: string;
    description: string;
    linkedIndicator?: string;
    evidence: EvidenceRules;
  };
  submissions: ObligationSubmission[];
}
export interface ActivitySchedule {
  id: Id;
  appliesTo: string;
  anchor:
    | "contract_signed_date"
    | "provider_first_class_start"
    | "training_planned_start"
    | "site_first_class_start"
    | "class_start"
    | "class_end";
  openOffset: number;
  dueOffset: number;
  graceDays: number;
  repeatEvery?: number;
  repeatCount?: number;
  breakdownExtends: boolean;
  active: boolean;
  legacy?: boolean;
}
export interface ActivityDefinition {
  id: Id;
  code: string;
  name: string;
  scope: "provider" | "training" | "site" | "class";
  description?: string;
  linkedIndicator?: string;
  recurrence: "once" | "monthly";
  active: boolean;
  evidence: EvidenceRules;
  schedules: ActivitySchedule[];
}
export interface VerificationPlan {
  id: Id;
  indicatorCode: string;
  indicatorName: string;
  version: number;
  status: "draft" | "active" | "retired";
  populationMetric: string;
  strata: string[];
  z: number;
  p: number;
  e: number;
  nonResponse: number;
  reservePct: number;
  minPerStratum: number;
  tiering: "single" | "two_tier";
  estimator: "wilson_one_sided" | "wilson_two_sided" | "clopper_pearson" | "simple_rate";
  ciZ: number;
  decisionRule: "ci_vs_target" | "point_vs_target";
  maxAttempts: number;
  effectiveFrom: DateOnly;
}
export type StatusCode = "V-COMP" | "V-NCOMP" | "V-UNR" | "V-REF" | "V-INC";
export interface VerificationSubject {
  id: Id;
  key: string;
  runId: Id;
  traineeId: Id;
  name: string;
  phone: string;
  phoneAlt?: string;
  providerName: string;
  trainingTitle: string;
  level: string;
  location: string;
  sex: string;
  stratum: string;
  role: "primary" | "reserve" | "replacement";
  enumerator?: string;
  attempts: { no: number; at: Iso; outcome: string; note?: string }[];
  status?: StatusCode;
  supervisor: "pending" | "approved" | "rejected";
  answers?: Record<string, string>;
  indicatorName: string;
  evidence: { id: Id; name: string; type?: string }[];
}
export interface RunDetail {
  run: VerificationRun & {
    seed: string;
    drawnAt: Iso;
    targetUsed: number;
    planTiering: "single" | "two_tier";
    estimator: string;
    parameters: {
      z: number;
      p: number;
      e: number;
      nonResponse: number;
      reservePct: number;
      ciZ: number;
    };
  };
  strata: {
    key: string;
    location: string;
    sex: string;
    population: number;
    primary: number;
    reserve: number;
    completed: number;
  }[];
  statusCounts: Record<StatusCode | "pending", number>;
  blockers: number;
}
export interface SamplePreview {
  population: number;
  n0: number;
  nFpc: number;
  nTarget: number;
  reserves: number;
  strata: { location: string; sex: string; population: number; primary: number; reserve: number }[];
  warnings: string[];
  reportsSubmitted: boolean;
}
export interface AuditEvent {
  id: Id;
  at: Iso;
  actor: string;
  module: string;
  action: string;
  entity: string;
  summary: string;
  before?: Record<string, unknown>;
  after?: Record<string, unknown>;
  legacy: boolean;
}
export interface Session {
  id: Id;
  device: string;
  ip: string;
  lastUsed: Iso;
  current: boolean;
}
export interface ReminderRule {
  key: string;
  label: string;
  offsets: number[];
  repeatAfter?: number;
  severity: "info" | "warning" | "critical";
  email: boolean;
  enabled: boolean;
}
export interface OutboxItem {
  id: Id;
  to: string;
  subject: string;
  template: string;
  status: "queued" | "sending" | "sent" | "failed" | "dead";
  attempts: number;
  createdAt: Iso;
  sentAt?: Iso;
  error?: string;
}
export interface MailSettings {
  host: string;
  port: number;
  security: "none" | "starttls" | "tls";
  user: string;
  fromName: string;
  fromEmail: string;
  enabled: boolean;
  passwordSet: boolean;
}
export interface ProjectSettings {
  id: Id;
  code: string;
  title: string;
  donor: string;
  description: string;
  start: DateOnly;
  end: DateOnly;
  overEnrolmentPct: number;
  attendanceThreshold: number;
  exemptDays: number;
  lateDays: number;
  lateApproval: boolean;
  grievanceSlaDays: number;
  rosterFreezeOffset: number;
  registrationOpen: boolean;
  registrationCloseNote?: string;
  registrationClosedAt?: string;
  registrationClosedBy?: string;
  remindersOn: boolean;
  require2faRoles: RoleCode[];
  enforce2fa?: boolean;
}
export interface Holiday {
  id: Id;
  date: DateOnly;
  label: string;
  kind: "national" | "religious" | "local" | "programme";
  locationCode?: string;
}
export interface MasterLocation {
  id: Id;
  code: string;
  name: string;
  regionCode: string;
  active: boolean;
}
export interface RegionAlias {
  alias: string;
  canonical: string;
}
export interface Breakdown {
  id: Id;
  providerCode: string;
  trainingTitle: string;
  scopeLabel: string;
  classId?: Id;
  start: DateOnly;
  end: DateOnly;
  sessionsAffected: number;
  reason: string;
  status: "requested" | "approved" | "rejected" | "cancelled";
  requestedBy: string;
  requestedAt: Iso;
  decidedBy?: string;
  decisionNote?: string;
  newEnd?: DateOnly;
}
export interface NotificationPref {
  type: string;
  label: string;
  inApp: boolean;
  email: "immediate" | "daily_digest" | "off";
  mandatory: boolean;
}
export interface RoleDef {
  code: RoleCode | string;
  label: string;
  system: boolean;
  providerBound: boolean;
  locked?: boolean;
  members: number;
  permissions: string[];
  /** The permissions a system role starts with. */
  defaults?: string[];
}
export interface PermissionDef {
  key: string;
  category: string;
  label: string;
  /** May be given to a provider role. */
  providerAllowed: boolean;
}
export interface ProjectSummary {
  id: Id;
  code: string;
  title: string;
  roleCode: string;
  roleLabel: string;
  donor?: string | null;
  location?: string | null;
  start?: string | null;
  end?: string | null;
  providerName?: string;
  trainees: number;
  providers: number;
}
