import type { ParcelDetail } from "@/app/api/eterra/search/route";
import type { OwnerSearchResult } from "@/app/api/eterra/search-owner/route";

/* ------------------------------------------------------------------ */
/*  Types                                                              */
/* ------------------------------------------------------------------ */

export type UatEntry = {
  siruta: string;
  name: string;
  county?: string;
  workspacePk?: number;
  localFeatures?: number;
};

export type SessionStatus = {
  connected: boolean;
  username?: string;
  connectedAt?: string;
  activeJobCount: number;
  activeJobPhase?: string;
  /** eTerra platform health */
  eterraAvailable?: boolean;
  /** True when eTerra is in maintenance */
  eterraMaintenance?: boolean;
  /** Human-readable health message */
  eterraHealthMessage?: string;
};

export type ExportProgress = {
  jobId: string;
  downloaded: number;
  total?: number;
  status: "running" | "done" | "error" | "unknown";
  phase?: string;
  message?: string;
  note?: string;
  phaseCurrent?: number;
  phaseTotal?: number;
};

export type SyncRunInfo = {
  id: string;
  layerId: string;
  status: string;
  totalRemote: number;
  totalLocal: number;
  newFeatures: number;
  removedFeatures: number;
  startedAt: string;
  completedAt?: string;
};

export type DbUatSummary = {
  siruta: string;
  uatName: string;
  county: string | null;
  layers: {
    layerId: string;
    count: number;
    enrichedCount: number;
    noGeomCount: number;
    lastSynced: string | null;
  }[];
  totalFeatures: number;
  totalEnriched: number;
  totalNoGeom: number;
};

export type DbSummary = {
  uats: DbUatSummary[];
  totalFeatures: number;
  totalUats: number;
};

/* ------------------------------------------------------------------ */
/*  Helpers                                                            */
/* ------------------------------------------------------------------ */

export const normalizeText = (text: string) =>
  text
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .trim();

export function formatDate(iso?: string | null) {
  if (!iso) return "—";
  return new Date(iso).toLocaleDateString("ro-RO", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

export function formatArea(val?: number | null) {
  if (val == null) return "—";
  return val.toLocaleString("ro-RO", { maximumFractionDigits: 2 }) + " mp";
}

/** Format ISO date as DD.MM.YYYY (no time) */
export function formatShortDate(iso?: string | null) {
  if (!iso) return "—";
  const d = new Date(iso);
  const dd = String(d.getDate()).padStart(2, "0");
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  return `${dd}.${mm}.${d.getFullYear()}`;
}

export function relativeTime(date: Date | null) {
  if (!date) return "niciodată";
  const mins = Math.floor((Date.now() - date.getTime()) / 60_000);
  if (mins < 1) return "acum";
  if (mins < 60) return `acum ${mins} min`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `acum ${hours}h`;
  const days = Math.floor(hours / 24);
  return `acum ${days}z`;
}

/* Re-export for convenience */
export type { ParcelDetail, OwnerSearchResult };
