import { hatcheryApplications, HatcheryApplication } from "@/data/dummyData"; const LOCAL_KEY = "hatchery_local_applications"; function readLocal(): HatcheryApplication[] { if (typeof window === "undefined") return []; try { const raw = localStorage.getItem(LOCAL_KEY); if (!raw) return []; const parsed = JSON.parse(raw); if (!Array.isArray(parsed)) return []; return parsed as HatcheryApplication[]; } catch { return []; } } function writeLocal(apps: HatcheryApplication[]) { if (typeof window === "undefined") return; try { localStorage.setItem(LOCAL_KEY, JSON.stringify(apps)); } catch { // ignore } } export function getUserHatcheryApplications(userId?: string | null): HatcheryApplication[] { if (!userId) return []; const base = hatcheryApplications.filter((app) => app.applicantId === userId); const local = readLocal().filter((app) => app.applicantId === userId); return [...base, ...local].sort( (a, b) => new Date(b.submittedDate).getTime() - new Date(a.submittedDate).getTime(), ); } export function getHatcheryApplicationById(id: string): HatcheryApplication | undefined { const base = hatcheryApplications.find((app) => app.id === id); if (base) return base; const local = readLocal().find((app) => app.id === id); return local; } export interface NewHatcheryApplicationInput { hatcheryName: string; ownerName: string; species: string; capacity: string; state: string; district: string; address: string; email: string; phone: string; } export function createHatcheryApplicationForUser( userId: string, data: NewHatcheryApplicationInput, ): HatcheryApplication { const now = new Date(); const id = `HL${now.getTime()}`; const applicationNo = `SHAP/H/${now.getFullYear()}/${now.getTime().toString().slice(-4)}`; const app: HatcheryApplication = { id, applicationNo, hatcheryName: data.hatcheryName, ownerName: data.ownerName, applicantId: userId, email: data.email, phone: data.phone, state: data.state, district: data.district, address: data.address, species: data.species, capacity: data.capacity, status: "submitted", currentStage: "submission", submittedDate: now.toISOString().slice(0, 10), assignedFOI: undefined, assignedFO: undefined, assignedCCOfficer: undefined, assignedAuditor: undefined, paymentStatus: "pending", paymentAmount: 0, audits: [], certificates: [], }; const all = readLocal(); writeLocal([...all, app]); return app; }