// seeds/publicPortalTemplates.seed.cjs
const mongoose = require('mongoose');
const path = require('path');
const fs = require('fs').promises;
require('dotenv').config({ path: path.join(__dirname, '../.env') }); // safer path

const PublicPortalTemplate = require('../models/PublicPortalTemplate.cjs');

// ────────────────────────────────────────────────
// Load large template from external file (strongly recommended)
async function loadDefaultHtml() {
  try {
    const templatePath = path.join(__dirname, 'defaults/public-portal-default.html');
    return await fs.readFile(templatePath, 'utf-8');
  } catch (err) {
    console.error('Failed to load default HTML template:', err);
    process.exit(1);
  }
}

// You can also load cssContent from file if it grows
const DEFAULT_TEMPLATE = {
  name: 'Default Public Requisition Portal',
  description: 'Modern dark-sidebar layout matching the original React component',
  htmlContent: '', // will be filled asynchronously
  cssContent: `
    /* Custom overrides / additional styles */
    .rounded-custom { border-radius: 2rem; }
    input, select, textarea {
      transition: all 0.2s ease;
    }
    /* ... more default styles if needed ... */
  `,
  logoOverride: null,
  primaryColor: '#3b82f6',
  accentColor: '#1e40af',
  checkoutBackground: '#0f172a',     // slate-900
  checkoutTextColor: '#f8fafc',
  isDefault: true,
  isBuiltIn: true,
  // company: null,           // left out → null by default
  // createdBy: null,
};

async function seed() {
  let connection;

  try {
    // Connect (reuse existing if already connected)
    if (mongoose.connection.readyState === 0) {
      connection = await mongoose.connect(process.env.MONGODB_URI, {
        serverSelectionTimeoutMS: 5000,
      });
      console.log('Connected to MongoDB');
    } else {
      console.log('Using existing MongoDB connection');
    }

    // Load the large HTML content
    DEFAULT_TEMPLATE.htmlContent = await loadDefaultHtml();

    // Check for existing built-in template by unique marker
    const existing = await PublicPortalTemplate.findOne({
      name: DEFAULT_TEMPLATE.name,
      isBuiltIn: true,
    }).lean();

    if (existing) {
      console.log(`Built-in template "${DEFAULT_TEMPLATE.name}" already exists → skipping`);
      return;
    }

    const template = new PublicPortalTemplate(DEFAULT_TEMPLATE);
    await template.save();

    console.log(`Successfully seeded built-in template: ${template.name} (${template._id})`);

  } catch (error) {
    console.error('Seeding failed:', error.message);
    if (error.stack) console.error(error.stack.split('\n').slice(0, 5).join('\n'));
    process.exitCode = 1;
  } finally {
    // Only disconnect if we created the connection
    if (connection) {
      await mongoose.disconnect();
      console.log('Disconnected from MongoDB');
    }
  }
}

// Run the seed
seed();