// File-based JSON store for member vouchers.
// Each voucher: { code, tier, addedAt }

import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const STORE_PATH = path.join(__dirname, "..", "data", "vouchers.json");

function ensureDir() {
  const dir = path.dirname(STORE_PATH);
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}

function readAll() {
  ensureDir();
  if (!fs.existsSync(STORE_PATH)) return [];
  try {
    return JSON.parse(fs.readFileSync(STORE_PATH, "utf-8"));
  } catch {
    return [];
  }
}

function writeAll(list) {
  ensureDir();
  fs.writeFileSync(STORE_PATH, JSON.stringify(list, null, 2));
}

export function listVouchers() {
  return readAll();
}

export function addVoucher({ code, tier = "standard", whatsapp = "", duration = "1bulan", durationDays = 30, dailyLimit = 3 }) {
  const cleanWhatsapp = whatsapp.trim();
  let cleanCode = code ? code.trim().toUpperCase() : "";

  if (!cleanCode) {
    if (!cleanWhatsapp) {
      throw new Error("Nomor Whatsapp Member wajib diisi jika Kode Voucher dikosongkan");
    }
    const digits = cleanWhatsapp.replace(/\D/g, "");
    if (digits.length < 5) {
      throw new Error("Nomor Whatsapp harus memiliki minimal 5 digit angka");
    }
    const last5 = digits.slice(-5);
    cleanCode = `TEKNO-${last5}`;
  }

  const list = readAll();
  if (list.some((v) => v.code === cleanCode)) {
    throw new Error(`Voucher "${cleanCode}" sudah terdaftar`);
  }

  // Calculate active period (expiresAt)
  let days = 30;
  if (duration === "custom") {
    days = parseInt(durationDays, 10);
    if (isNaN(days) || days <= 0) {
      throw new Error("Masa aktif (hari) harus berupa angka positif");
    }
  }
  const expiresAt = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toISOString();

  // Validate daily limit
  const limit = parseInt(dailyLimit, 10);
  if (isNaN(limit) || limit <= 0) {
    throw new Error("Limit harian generate harus berupa angka positif");
  }

  const voucher = {
    code: cleanCode,
    tier: tier.toLowerCase() === "pro" ? "pro" : "standard",
    whatsapp: cleanWhatsapp,
    duration,
    durationDays: days,
    expiresAt,
    dailyLimit: limit,
    usage: {},
    addedAt: new Date().toISOString(),
  };

  list.push(voucher);
  writeAll(list);
  return voucher;
}

export function deleteVoucher(code) {
  const cleanCode = code.trim().toUpperCase();
  const list = readAll();
  const idx = list.findIndex((v) => v.code === cleanCode);
  if (idx < 0) return false;
  
  list.splice(idx, 1);
  writeAll(list);
  return true;
}

export function validateVoucher(code) {
  if (!code) return { ok: false, error: "Kode voucher harus diisi" };
  const cleanCode = code.trim().toUpperCase();
  const list = readAll();
  const voucher = list.find((v) => v.code === cleanCode);
  
  if (!voucher) {
    return { ok: false, error: "Kode voucher tidak valid" };
  }
  
  // Check active period
  if (voucher.expiresAt && Date.now() > new Date(voucher.expiresAt).getTime()) {
    return { ok: false, error: "Masa aktif voucher sudah habis (expired)" };
  }
  
  return { ok: true, tier: voucher.tier, voucher };
}

export function incrementUsage(code) {
  const cleanCode = code.trim().toUpperCase();
  const list = readAll();
  const idx = list.findIndex((v) => v.code === cleanCode);
  if (idx >= 0) {
    const todayStr = new Date().toISOString().split("T")[0];
    if (!list[idx].usage) list[idx].usage = {};
    list[idx].usage[todayStr] = (list[idx].usage[todayStr] || 0) + 1;
    writeAll(list);
    return true;
  }
  return false;
}
