import 'dotenv/config';
import { drizzle } from "drizzle-orm/node-postgres";
import pg from "pg";
import { eq } from "drizzle-orm";
import bcrypt from "bcryptjs";
import { users } from "../shared/models/auth";
import { userProfiles } from "../shared/schema";

const { Pool } = pg;

async function createAdmin() {
  if (!process.env.DATABASE_URL) {
    console.error("ERROR: DATABASE_URL is not set. Make sure your .env file exists and contains DATABASE_URL.");
    process.exit(1);
  }

  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
  const db = drizzle(pool);

  const adminEmail = "admin@madares.online";
  const adminPassword = "Admin@123456";

  try {
    const [existingAdmin] = await db.select().from(users).where(eq(users.email, adminEmail));

    if (existingAdmin) {
      const hashedPassword = await bcrypt.hash(adminPassword, 10);
      await db.update(users).set({
        password: hashedPassword,
        emailVerified: true,
        updatedAt: new Date(),
      }).where(eq(users.id, existingAdmin.id));

      const [existingProfile] = await db.select().from(userProfiles).where(eq(userProfiles.userId, existingAdmin.id));
      if (!existingProfile) {
        await db.insert(userProfiles).values({
          userId: existingAdmin.id,
          role: "admin",
          preferredLanguage: "ar",
        });
      }

      console.log("Admin user updated successfully!");
    } else {
      const hashedPassword = await bcrypt.hash(adminPassword, 10);
      const [adminUser] = await db.insert(users).values({
        email: adminEmail,
        password: hashedPassword,
        firstName: "مدير",
        lastName: "النظام",
        authProvider: "email",
        emailVerified: true,
      }).returning();

      await db.insert(userProfiles).values({
        userId: adminUser.id,
        role: "admin",
        preferredLanguage: "ar",
      });

      console.log("Admin user created successfully!");
    }

    console.log("Email: admin@madares.online");
    console.log("Password: Admin@123456");
  } catch (error) {
    console.error("Error:", error);
  } finally {
    await pool.end();
    process.exit(0);
  }
}

createAdmin();
