import "dotenv/config";
import mongoose from "mongoose";
import Admin from "../models/Admin.js";
import { connectDB, disconnectDB } from "../config/database.js";
import logger from "../utils/logger.js";

/**
 * Admin Seeder
 * Creates default admin user if it doesn't exist
 */
const seedAdmin = async () => {
  try {
    // Connect to database
    await connectDB();
    logger.info("Connected to database for seeding");

    // Default admin data - Only one admin user allowed
    const defaultAdmin = {
      email: process.env.ADMIN_EMAIL || "admin@samaa.com",
      password: process.env.ADMIN_PASSWORD || "Admin@123",
      name: process.env.ADMIN_NAME || "Admin User",
      isActive: true,
    };

    // Check if admin already exists
    const existingAdmin = await Admin.findOne({ email: defaultAdmin.email });

    if (existingAdmin) {
      logger.warn("Admin already exists", {
        email: defaultAdmin.email,
      });
      console.log("\n⚠️  Admin already exists with email:", defaultAdmin.email);
      console.log("   Skipping admin creation...\n");
      await disconnectDB();
      process.exit(0);
    }

    // Create admin
    const admin = await Admin.create(defaultAdmin);

    logger.info("Admin created successfully", {
      email: admin.email,
    });

    console.log("\n✅ Admin created successfully!");
    console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    console.log("📧 Email:", admin.email);
    console.log("🔑 Password:", defaultAdmin.password);
    console.log("👤 Name:", admin.name);
    console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
    console.log("⚠️  Please change the default password after first login!\n");
    console.log("ℹ️  Only this admin user can login to the system.\n");

    // Disconnect from database
    await disconnectDB();
    process.exit(0);
  } catch (error) {
    logger.error("Error seeding admin", error);
    console.error("\n❌ Error creating admin:", error.message);
    await disconnectDB();
    process.exit(1);
  }
};

// Run seeder
seedAdmin();

