import type { ContractStatus, LegalCaseSeverity, LegalCaseStatus, LegalCaseType, LegalJurisdictionLevel } from "@prisma/client";
import { z } from "zod";

export type LegalKpiSnapshot = {
  openCases: number;
  highSeverityCases: number;
  amountAtRisk: number;
  resolvedCases: number;
};

export type LegalCaseView = {
  id: string;
  contractId: string | null;
  caseType: LegalCaseType;
  severity: LegalCaseSeverity;
  counterparty: string;
  description: string;
  amountAtRisk: number | null;
  status: LegalCaseStatus;
  openedAt: string;
  resolvedAt: string | null;
  createdAt: string;
  updatedAt: string;
};

export type LegalContractOptionView = {
  id: string;
  title: string;
  contractNumber: string | null;
  counterpartyEntity: string;
  status: ContractStatus;
};

export type DiagnosisAnswers = {
  breachType: "contract_breach" | "payment_retention" | "unjust_sanction" | "contract_dispute" | null;
  processStage: "none" | "informal_notice" | "formal_notice" | "ongoing_claim" | "trial" | null;
  evidenceLevel: "none" | "basic" | "solid" | "robust" | null;
  urgency: "low" | "medium" | "high" | null;
  objective: "payment" | "correction" | "challenge" | "mediation" | null;
  amountAtRisk: number | null;
};

export type DiagnosisRecommendation = {
  suggestedSeverity: LegalCaseSeverity;
  suggestedCaseType: LegalCaseType;
  suggestedRoute: EscalationRouteStep[];
  recommendedTemplates: LegalTemplateKey[];
  notes: string[];
};

export type EscalationRouteStep = {
  key: "formal_requirement" | "administrative_conciliation" | "oic_complaint" | "sfp_or_state_challenge" | "jurisdictional_path";
  title: string;
  estimatedWindow: string;
  checklist: string[];
  requiresLawyer: boolean;
  dependsOn: string | null;
};

export type EscalationStepProgress = EscalationRouteStep & {
  completedAt: string | null;
  notes: string;
  isBlocked: boolean;
};

export type LegalTemplateKey =
  | "general_delivery_record"
  | "breach_disagreement_letter"
  | "payment_release_request"
  | "sanctions_challenge_resource";

export type LegalTemplateView = {
  key: LegalTemplateKey;
  category: "general" | "breach" | "payment" | "sanctions";
  title: string;
  body: string;
};

export type LegalDirectoryEntityView = {
  id: string;
  jurisdictionLevel: LegalJurisdictionLevel;
  name: string;
  scopeTags: string[];
  websiteUrl: string | null;
  phone: string | null;
  email: string | null;
  stateCode: string | null;
  municipalityCode: string | null;
};

export type LegalDocumentGenerationInput = {
  legalCaseId: string | null;
  caseType: LegalCaseType;
  severity: LegalCaseSeverity;
  templateKey: LegalTemplateKey | null;
  counterparty: string;
  companyName: string;
  amountAtRisk: number | null;
  description: string;
  objective: string;
};

export type LegalDocumentGenerationOutput = {
  title: string;
  content: string;
  engine: "openai_json_object" | "template_fallback";
  model: string | null;
  warnings: string[];
  usage:
    | {
        promptTokens: number | null;
        completionTokens: number | null;
        totalTokens: number | null;
      }
    | null;
};

export const LegalCaseCreateInputSchema = z.object({
  contractId: z.string().trim().min(1).optional().nullable(),
  caseType: z.enum(["CONTRACT_BREACH", "PAYMENT_RETENTION", "UNJUST_SANCTION", "CONTRACT_DISPUTE"]),
  severity: z.enum(["LOW", "MEDIUM", "HIGH"]).default("MEDIUM"),
  counterparty: z.string().trim().min(2).max(220),
  description: z.string().trim().min(10).max(8000),
  amountAtRisk: z.number().finite().nonnegative().optional().nullable(),
  status: z.enum(["OPEN", "IN_PROGRESS", "ESCALATED", "RESOLVED", "CLOSED"]).optional(),
});

export const LegalCaseUpdateInputSchema = z.object({
  severity: z.enum(["LOW", "MEDIUM", "HIGH"]).optional(),
  status: z.enum(["OPEN", "IN_PROGRESS", "ESCALATED", "RESOLVED", "CLOSED"]).optional(),
  resolvedAt: z.string().datetime().optional().nullable(),
  description: z.string().trim().max(8000).optional(),
  amountAtRisk: z.number().finite().nonnegative().optional().nullable(),
  counterparty: z.string().trim().min(2).max(220).optional(),
});

export const LegalDiagnosisStartInputSchema = z.object({
  contractId: z.string().trim().min(1).optional().nullable(),
});

export const LegalDiagnosisAnswerInputSchema = z.object({
  diagnosisId: z.string().trim().min(1),
  stepIndex: z.number().int().min(1).max(4),
  answers: z.record(z.string(), z.unknown()),
  finalize: z.boolean().optional(),
});

export const LegalDirectoryFiltersSchema = z.object({
  jurisdictionLevel: z.enum(["FEDERAL", "STATE", "MUNICIPAL"]).optional(),
  stateCode: z.string().trim().max(12).optional(),
  q: z.string().trim().max(120).optional(),
});

export const LegalDocumentGenerateInputSchema = z.object({
  legalCaseId: z.string().trim().min(1).optional().nullable(),
  caseType: z.enum(["CONTRACT_BREACH", "PAYMENT_RETENTION", "UNJUST_SANCTION", "CONTRACT_DISPUTE"]),
  severity: z.enum(["LOW", "MEDIUM", "HIGH"]),
  templateKey: z
    .enum(["general_delivery_record", "breach_disagreement_letter", "payment_release_request", "sanctions_challenge_resource"])
    .optional()
    .nullable(),
  counterparty: z.string().trim().min(2).max(220),
  companyName: z.string().trim().min(2).max(220),
  amountAtRisk: z.number().finite().nonnegative().optional().nullable(),
  description: z.string().trim().min(10).max(8000),
  objective: z.string().trim().min(2).max(600),
  title: z.string().trim().max(220).optional().nullable(),
});

export type LegalCaseCreateInput = z.infer<typeof LegalCaseCreateInputSchema>;
export type LegalCaseUpdateInput = z.infer<typeof LegalCaseUpdateInputSchema>;
export type LegalDiagnosisStartInput = z.infer<typeof LegalDiagnosisStartInputSchema>;
export type LegalDiagnosisAnswerInput = z.infer<typeof LegalDiagnosisAnswerInputSchema>;
export type LegalDirectoryFilters = z.infer<typeof LegalDirectoryFiltersSchema>;
export type LegalDocumentGenerateInput = z.infer<typeof LegalDocumentGenerateInputSchema>;
