const fs = require('fs');
const path = require('path');
const url = require('url');
// const { connectDB } = require('./connect');
const { HomeModel } = require('../models/Home');
const { EventModel } = require('../models/Event');
const { PostModel } = require('../models/Post');

const __dirname = path.dirname(url.fileURLToPath(import.meta.url));

async function run() {
  // await connectDB();

  // Adatta il percorso se frontend e backend sono separati
  const samplePath = path.resolve(__dirname, '../../../src/server/mocks/home.sample.json');
  const raw = fs.readFileSync(samplePath, 'utf-8');
  const json = JSON.parse(raw);

  // Home snapshot
  await HomeModel.deleteMany({});
  await HomeModel.create({
    hero: json.hero,
    pillars: json.pillars,
    testimonials: json.testimonials,
    gallery: json.gallery,
    faq: json.faq,
    partners: json.partners,
    posts: json.posts
  });

  // Events
  await EventModel.deleteMany({});
  await EventModel.insertMany(json.events.map((e) => ({
    title: e.title,
    start: new Date(e.start),
    end: e.end ? new Date(e.end) : undefined,
    place: e.place,
    teaser: e.teaser,
    cover: e.cover,
    to: e.to
  })));

  // Posts
  await PostModel.deleteMany({});
  await PostModel.insertMany(json.posts.map((p) => ({
    title: p.title,
    date: new Date(p.date),
    category: p.category,
    teaser: p.teaser,
    cover: p.cover,
    to: p.to,
    bodyMd: `# ${p.title}\n\n${p.teaser}\n`
  })));

  console.log('[seed] done');
  process.exit(0);
}

run().catch((e) => { console.error(e); process.exit(1); });
