/**
 * Single source of truth for dashboard v2 dev personas.
 * Field names and values must match specs/contracts/dashboard-v2.openapi.yaml exactly.
 * Agent F (core-api seed) and Agent MOCK import from here — never duplicate literals.
 */

import type { FarmerDashboardResponse } from "@/lib/api-types";

/** Demo userId suffix convention: …001 identity, …002 finance, …003 inputs */
export const DASHBOARD_PERSONA_IDS = {
  islomjon: "usr-demo-islomjon-001",
  agrobankCase: "usr-demo-agrobank-002",
  burkinaInputs: "usr-demo-burkina-003",
} as const;

export type DashboardPersonaKey = keyof typeof DASHBOARD_PERSONA_IDS;

/** Tashkent region — mockup GIS polygon (WGS84 GeoJSON) */
export const MOCK_POLYGON_TASHKENT = {
  type: "Polygon" as const,
  coordinates: [
    [
      [69.2784, 41.3128],
      [69.2856, 41.3128],
      [69.2856, 41.3182],
      [69.2784, 41.3182],
      [69.2784, 41.3128],
    ],
  ],
};

const ISLOMJON_COMPLIANCE = [
  { key: "gis", label: "GIS boundary verified", passed: true },
  { key: "ekyc", label: "eKYC identity verified", passed: true },
  { key: "land", label: "Land tenure documented", passed: true },
  { key: "documents", label: "Land evidence complete", passed: true },
  { key: "scoring", label: "Eligibility scoring passed", passed: true },
  { key: "regulatory", label: "Regulatory compliance", passed: true },
];

const ISLOMJON_YIELD_HISTORY = [
  { year: 2020, yieldTHa: 3.2, crop: "cotton" },
  { year: 2021, yieldTHa: 3.5, crop: "cotton" },
  { year: 2022, yieldTHa: 3.8, crop: "cotton" },
  { year: 2023, yieldTHa: 4.1, crop: "cotton" },
  { year: 2024, yieldTHa: 3.9, crop: "cotton" },
];

const AGROBANK_STAGES = [
  { label: "Case Created", completed: true, timestamp: "2024-05-23T10:15:00.000Z" },
  { label: "Eligibility Check", completed: true, timestamp: "2024-05-23T11:02:00.000Z" },
  { label: "Document Review", completed: true, timestamp: "2024-05-23T13:45:00.000Z" },
  { label: "Routed to Institution", completed: true, timestamp: "2024-05-23T14:30:00.000Z" },
  { label: "Institution Assessment", completed: false },
  { label: "Credit Committee", completed: false },
  { label: "Final Decision", completed: false },
];

const BURKINA_CATALOG = [
  {
    category: "Seed",
    items: [
      { id: "seed-cotton-xl", name: "Cotton XL Hybrid", unitPrice: 125000, currency: "UZS" },
      { id: "seed-wheat-durum", name: "Durum Wheat Premium", unitPrice: 89000, currency: "UZS" },
    ],
  },
  {
    category: "Fertiliser",
    items: [
      { id: "fert-npk-15", name: "NPK 15-15-15", unitPrice: 450000, currency: "UZS" },
      { id: "fert-urea", name: "Urea 46%", unitPrice: 380000, currency: "UZS" },
    ],
  },
  {
    category: "Equipment",
    items: [
      { id: "eq-drip-kit", name: "Drip Irrigation Kit", unitPrice: 2500000, currency: "UZS" },
    ],
  },
];

export const DASHBOARD_MOCKUP_PERSONAS: Record<DashboardPersonaKey, FarmerDashboardResponse> = {
  islomjon: {
    userId: DASHBOARD_PERSONA_IDS.islomjon,
    phone: "+998901110001",
    sessionId: "sess-demo-islomjon-001",
    applicationStatus: "completed",
    score: 742,
    eligibility: "eligible",
    identity: {
      fullName: "Islomjon Abdullaev",
      farmName: "Islomjon Abdullaev",
      farmerId: "AGID-FMR-00142",
      district: "Tashkent",
      gender: "male",
      kycStatus: "verified",
      farmSizeHa: "4.52",
      landOwnership: "owner",
      hasGisMapping: true,
      documentCompleteness: 100,
      ekyc: {
        photoUrl: "/agnet-assets/demo-ekyc.jpg",
        dob: "1985-03-14",
        aadhaarMasked: "XXXX-XXXX-4521",
        mobileMasked: "+998 ** *** 00 01",
      },
      gis: {
        areaHa: 4.52,
        lat: 41.3155,
        lng: 69.282,
        polygonGeoJson: MOCK_POLYGON_TASHKENT,
      },
      landEvidence: [
        { name: "Land Registry Certificate", type: "pdf", verified: true },
        { name: "Cadastral Survey Report", type: "pdf", verified: true },
        { name: "Tenure Agreement", type: "doc", verified: true },
      ],
      yieldHistory: ISLOMJON_YIELD_HISTORY,
      compliance: ISLOMJON_COMPLIANCE,
    },
    finance: null,
    trade: null,
    inputs: null,
  },

  agrobankCase: {
    userId: DASHBOARD_PERSONA_IDS.agrobankCase,
    phone: "+998901110002",
    sessionId: "sess-demo-agrobank-002",
    applicationStatus: "completed",
    score: 780,
    eligibility: "eligible",
    finance: {
      purpose: "working_capital",
      amount: "85000000",
      existingLoans: "12000000",
      monthlyIncome: "9500000",
      repaymentHistory: "good",
      caseId: "UZB-2024-05-000789",
      status: "under_review",
      riskPd: 0.038,
      riskRating: "B+",
      ifrs9Stage: 1,
      cbuClass: 2,
      eligibilityScore: 78,
      eligibilityLabel: "High",
      routedInstitution: {
        name: "Agrobank (UZ)",
        priority: "High",
        isBestMatch: true,
      },
      sla: {
        remainingHours: 18,
        totalHours: 48,
        dueAt: "2024-05-25T18:30:00.000Z",
      },
      bankMatches: [
        { name: "Agrobank (UZ)", score: 92, status: "routed" },
        { name: "Xalq Banki", score: 84, status: "view" },
        { name: "Ipak Yo'li Bank", score: 74, status: "view" },
        { name: "Mikrokreditbank", score: 68, status: "view" },
      ],
      documents: [
        { name: "ID / Passport", status: "verified" },
        { name: "Land Ownership / Lease", status: "verified" },
        { name: "GIS Field Report", status: "verified" },
        { name: "Crop Plan", status: "verified" },
        { name: "Photo (Farmer)", status: "verified" },
        { name: "Financial Statement", status: "pending" },
        { name: "Other Supporting Docs", status: "pending" },
      ],
      stages: AGROBANK_STAGES,
      satelliteImages: ["/agnet-assets/agnet-finance-dashboard.png"],
    },
    identity: {
      fullName: "Islomjon Abdullaev",
      farmName: "Islomjon Abdullaev",
      farmerId: "AGID-FMR-00289",
      region: "Tashkent",
      district: "Zangiota",
      gender: "male",
      kycStatus: "verified",
      farmSizeHa: "24.6",
      landOwnership: "owner",
      hasGisMapping: true,
      documentCompleteness: 100,
      gis: {
        areaHa: 24.6,
        lat: 41.3155,
        lng: 69.282,
        polygonGeoJson: MOCK_POLYGON_TASHKENT,
      },
    },
    trade: {
      crops: [
        {
          crop: "Wheat",
          variety: "Durum",
          season: "2024",
          expectedYield: "3.8",
        },
      ],
      buyerMatches: [],
      exportDocsComplete: false,
    },
    inputs: null,
  },

  burkinaInputs: {
    userId: DASHBOARD_PERSONA_IDS.burkinaInputs,
    phone: "+998901110003",
    sessionId: "sess-demo-burkina-003",
    applicationStatus: "completed",
    score: 710,
    eligibility: "conditional",
    inputs: {
      assets: [],
      recommendedInputs: [],
      kpis: {
        seed: 12,
        fertiliser: 8,
        equipment: 3,
        vouchers: 2,
        inTransit: 1,
      },
      suppliers: [
        { name: "AgroSupply UZ", logoUrl: "/agnet-assets/supplier-agrosupply.png", rating: 4.8 },
        { name: "Cotton Inputs Co.", rating: 4.5 },
        { name: "Burkina Agro Partners", rating: 4.2 },
      ],
      catalog: BURKINA_CATALOG,
      voucher: {
        code: "VCH-2026-8842",
        amount: 5000000,
        currency: "UZS",
        status: "active",
        paymentRoute: [
          { step: 1, label: "Voucher issued", completed: true },
          { step: 2, label: "Payment authorised", completed: true },
          { step: 3, label: "Supplier confirmed", completed: false },
          { step: 4, label: "Delivery dispatched", completed: false },
        ],
      },
      delivery: {
        trackingId: "DLV-2026-3318",
        status: "in_transit",
        eta: "2026-06-28T09:00:00.000Z",
        steps: [
          { label: "Order placed", completed: true, timestamp: "2026-06-25T08:00:00.000Z" },
          { label: "Warehouse packed", completed: true, timestamp: "2026-06-26T14:30:00.000Z" },
          { label: "In transit", completed: true, timestamp: "2026-06-27T06:00:00.000Z" },
          { label: "Delivered", completed: false, timestamp: null },
        ],
      },
    },
    identity: {
      fullName: "Amadou Diallo",
      farmName: "Diallo Cooperative Plot",
      farmerId: "AGID-FMR-00215",
      district: "Fergana",
      gender: "male",
      kycStatus: "verified",
      farmSizeHa: "3.80",
      landOwnership: "cooperative_member",
      hasGisMapping: true,
      documentCompleteness: 88,
    },
    finance: null,
    trade: null,
  },
};

export function getDashboardPersonaByUserId(userId: string): FarmerDashboardResponse | null {
  for (const key of Object.keys(DASHBOARD_MOCKUP_PERSONAS) as DashboardPersonaKey[]) {
    if (DASHBOARD_MOCKUP_PERSONAS[key].userId === userId) {
      return DASHBOARD_MOCKUP_PERSONAS[key];
    }
  }
  return null;
}

export function isDashboardPersonaUserId(userId: string): boolean {
  return getDashboardPersonaByUserId(userId) != null;
}
