import { mkdir, readFile, writeFile } from "fs/promises";
import path from "path";
import { dataDirectory } from "@/lib/runtime/config";
import type { ContactInquiry, InquiryStatus, RepairInquiry, SiteSettings, SmtpSettings } from "./types";

async function ensureDataDir() {
  await mkdir(dataDirectory, { recursive: true });
}

async function readJson<T>(fileName: string, fallback: T): Promise<T> {
  await ensureDataDir();
  try {
    const file = await readFile(path.join(dataDirectory, fileName), "utf8");
    return JSON.parse(file) as T;
  } catch {
    return fallback;
  }
}

async function writeJson<T>(fileName: string, value: T) {
  await ensureDataDir();
  await writeFile(path.join(dataDirectory, fileName), `${JSON.stringify(value, null, 2)}\n`, "utf8");
}

function id(prefix: string) {
  return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
}

function text(value: FormDataEntryValue | null) {
  return typeof value === "string" ? value.trim() : "";
}

export async function getContactInquiries() {
  return readJson<ContactInquiry[]>("contact-inquiries.json", []);
}

export async function getRepairInquiries() {
  return readJson<RepairInquiry[]>("repair-inquiries.json", []);
}

export async function addContactInquiry(form: FormData) {
  const inquiries = await getContactInquiries();
  const inquiry: ContactInquiry = {
    id: id("contact"),
    createdAt: new Date().toISOString(),
    status: "new",
    name: text(form.get("name")),
    email: text(form.get("email")),
    phone: text(form.get("phone")),
    subject: text(form.get("subject")) || "Kontaktanfrage",
    message: text(form.get("message")),
  };
  await writeJson("contact-inquiries.json", [inquiry, ...inquiries]);
  return inquiry;
}

export async function addRepairInquiry(form: FormData) {
  const inquiries = await getRepairInquiries();
  const inquiry: RepairInquiry = {
    id: id("repair"),
    createdAt: new Date().toISOString(),
    status: "new",
    name: text(form.get("name")),
    email: text(form.get("email")),
    phone: text(form.get("phone")),
    manufacturer: text(form.get("manufacturer")),
    model: text(form.get("model")),
    serialNumber: text(form.get("serialNumber")),
    deviceType: text(form.get("deviceType")),
    accessories: text(form.get("accessories")),
    opened: text(form.get("opened")),
    previousWork: text(form.get("previousWork")),
    description: text(form.get("description")),
  };
  await writeJson("repair-inquiries.json", [inquiry, ...inquiries]);
  return inquiry;
}

export async function updateContactStatus(id: string, status: InquiryStatus) {
  const inquiries = await getContactInquiries();
  await writeJson("contact-inquiries.json", inquiries.map((item) => item.id === id ? { ...item, status } : item));
}

export async function updateRepairStatus(id: string, status: InquiryStatus) {
  const inquiries = await getRepairInquiries();
  await writeJson("repair-inquiries.json", inquiries.map((item) => item.id === id ? { ...item, status } : item));
}

export async function getSiteSettings() {
  return readJson<SiteSettings>("site-settings.json", {
    companyName: "Funktechnik Schubert",
    phone: "",
    email: "info@funktechnik-schubert.de",
    address: "",
    openingHours: "",
    googleMapsEmbedUrl: "",
    socialLinks: "",
  });
}

export async function saveSiteSettings(form: FormData) {
  const settings: SiteSettings = {
    companyName: text(form.get("companyName")),
    phone: text(form.get("phone")),
    email: text(form.get("email")),
    address: text(form.get("address")),
    openingHours: text(form.get("openingHours")),
    googleMapsEmbedUrl: text(form.get("googleMapsEmbedUrl")),
    socialLinks: text(form.get("socialLinks")),
  };
  await writeJson("site-settings.json", settings);
  return settings;
}

export async function getSmtpSettings() {
  return readJson<SmtpSettings>("smtp-settings.json", {
    host: "",
    port: "587",
    username: "",
    fromAddress: "",
    replyToAddress: "",
    tls: true,
  });
}

export async function saveSmtpSettings(form: FormData) {
  const settings: SmtpSettings = {
    host: text(form.get("host")),
    port: text(form.get("port")),
    username: text(form.get("username")),
    fromAddress: text(form.get("fromAddress")),
    replyToAddress: text(form.get("replyToAddress")),
    tls: form.get("tls") === "on",
  };
  await writeJson("smtp-settings.json", settings);
  return settings;
}
