const fs = require('fs');
const path = require('path');

const BOXES_FILE = path.join(__dirname, '..', 'data', 'boxes.json');

const DEFAULT_BOXES = Array.from({ length: 8 }, (_, index) => ({
  id: `box-${index + 1}`,
  name: `Box ${index + 1}`,
  price: 0,
  image: '',
  description: '',
}));

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

  if (!fs.existsSync(BOXES_FILE)) {
    fs.writeFileSync(BOXES_FILE, JSON.stringify(DEFAULT_BOXES, null, 2));
  }
}

function normalizeBox(box = {}, index = 0) {
  return {
    id: box.id || `box-${index + 1}`,
    name: String(box.name || `Box ${index + 1}`).trim(),
    price: Number(box.price || 0),
    image: String(box.image || '').trim(),
    description: String(box.description || '').trim(),
  };
}

function readBoxes() {
  ensureBoxesFile();
  try {
    const raw = fs.readFileSync(BOXES_FILE, 'utf8');
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) {
      return DEFAULT_BOXES.map(normalizeBox);
    }
    const padded = Array.from({ length: 8 }, (_, index) => normalizeBox(parsed[index] || {}, index));
    return padded;
  } catch (error) {
    console.error('Error reading boxes file:', error);
    return DEFAULT_BOXES.map(normalizeBox);
  }
}

function writeBoxes(boxes = []) {
  ensureBoxesFile();
  const normalized = Array.from({ length: 8 }, (_, index) => normalizeBox(boxes[index] || {}, index));
  fs.writeFileSync(BOXES_FILE, JSON.stringify(normalized, null, 2));
  return normalized;
}

module.exports = {
  BOXES_FILE,
  readBoxes,
  writeBoxes,
};
