// Creates and seeds the Waseel database tables (local/self-hosted PostgreSQL).
// Usage: node scripts/seed-db.mjs   (reads DATABASE_URL from .env)

import pg from "pg";
import { readFileSync } from "fs";

const env = readFileSync(new URL("../.env", import.meta.url), "utf8");
const databaseUrl = env
  .split("\n")
  .find((l) => l.startsWith("DATABASE_URL="))
  ?.split("=")
  .slice(1)
  .join("=")
  .trim()
  .replace(/^"|"$/g, "");

if (!databaseUrl) {
  console.error("DATABASE_URL not found in .env");
  process.exit(1);
}

const pool = new pg.Pool({ connectionString: databaseUrl });

const sql = async (strings, ...values) => {
  const text = strings.reduce(
    (acc, chunk, i) => acc + chunk + (i < values.length ? `$${i + 1}` : ""),
    "",
  );
  const result = await pool.query(text, values);
  return result.rows;
};

// Migrate databases created during the Clerk era (clerk_id column, no UNIQUE email).
const clerkCol = await sql`
  SELECT 1 FROM information_schema.columns
  WHERE table_name = 'users' AND column_name = 'clerk_id'
`;
if (clerkCol.length > 0) {
  await sql`ALTER TABLE users DROP COLUMN clerk_id`;
  console.log("Dropped legacy clerk_id column from users.");
}

// Rebuild legacy tables where users.id / rides.user_id are not UUID.
const idType = await sql`
  SELECT data_type FROM information_schema.columns
  WHERE table_name = 'users' AND column_name = 'id'
`;
if (idType.length > 0 && idType[0]?.data_type !== "uuid") {
  console.log("Detected legacy non-UUID users schema, rebuilding users/rides...");
  await sql`DROP TABLE IF EXISTS rides`;
  await sql`DROP TABLE IF EXISTS users CASCADE`;
  console.log("Legacy users/rides tables dropped (test data only).");
}

await sql`CREATE TABLE IF NOT EXISTS users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) NOT NULL UNIQUE,
  phone VARCHAR(20),
  password_hash TEXT,
  google_sub TEXT UNIQUE,
  email_verified BOOLEAN NOT NULL DEFAULT FALSE,
  role VARCHAR(20),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`;

// For databases created before self-hosted auth existed.
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS role VARCHAR(20)`;
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS phone VARCHAR(20)`;
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS password_hash TEXT`;
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS google_sub TEXT`;
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT FALSE`;

// email must be UNIQUE for ON CONFLICT (email) upserts in register+api.ts.
const emailUnique = await sql`
  SELECT 1 FROM pg_constraint
  WHERE conrelid = 'users'::regclass AND contype = 'u'
    AND conkey @> ARRAY[
      (SELECT attnum::smallint FROM pg_attribute
       WHERE attrelid = 'users'::regclass AND attname = 'email')
    ]
`;
if (emailUnique.length === 0) {
  await sql`ALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE (email)`;
  console.log("Added unique constraint on users.email.");
}

await sql`CREATE TABLE IF NOT EXISTS email_verification_codes (
  email VARCHAR(255) PRIMARY KEY,
  code_hash TEXT NOT NULL,
  attempts INTEGER NOT NULL DEFAULT 0,
  expires_at TIMESTAMP NOT NULL
)`;

await sql`CREATE TABLE IF NOT EXISTS password_reset_codes (
  email VARCHAR(255) PRIMARY KEY,
  code_hash TEXT NOT NULL,
  attempts INTEGER NOT NULL DEFAULT 0,
  expires_at TIMESTAMP NOT NULL
)`;

await sql`CREATE TABLE IF NOT EXISTS drivers (
  id SERIAL PRIMARY KEY,
  first_name VARCHAR(100) NOT NULL,
  last_name VARCHAR(100) NOT NULL,
  profile_image_url TEXT,
  car_image_url TEXT,
  car_seats INTEGER NOT NULL,
  rating NUMERIC(2,1) NOT NULL
)`;

await sql`CREATE TABLE IF NOT EXISTS rides (
  ride_id SERIAL PRIMARY KEY,
  origin_address TEXT NOT NULL,
  destination_address TEXT NOT NULL,
  origin_latitude DOUBLE PRECISION NOT NULL,
  origin_longitude DOUBLE PRECISION NOT NULL,
  destination_latitude DOUBLE PRECISION NOT NULL,
  destination_longitude DOUBLE PRECISION NOT NULL,
  ride_time INTEGER NOT NULL,
  fare_price INTEGER NOT NULL,
  payment_status VARCHAR(50) NOT NULL,
  driver_id INTEGER NOT NULL REFERENCES drivers(id),
  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`;

const count = await sql`SELECT COUNT(*)::int AS n FROM drivers`;
if (count[0].n === 0) {
  await sql`INSERT INTO drivers
    (first_name, last_name, profile_image_url, car_image_url, car_seats, rating)
  VALUES
    ('Karim', 'Haddad', 'https://randomuser.me/api/portraits/men/32.jpg', 'https://images.unsplash.com/photo-1555215695-3004980ad54e?w=600', 4, 4.8),
    ('Rana', 'Khalil', 'https://randomuser.me/api/portraits/women/44.jpg', 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=600', 4, 4.9),
    ('Omar', 'Chehab', 'https://randomuser.me/api/portraits/men/75.jpg', 'https://images.unsplash.com/photo-1580273916550-e323be2ae537?w=600', 4, 4.6),
    ('Layal', 'Abou-Jaoude', 'https://randomuser.me/api/portraits/women/68.jpg', 'https://images.unsplash.com/photo-1590362891991-f776e747a588?w=600', 2, 4.7)`;
  console.log("Seeded 4 drivers.");
} else {
  console.log(`Drivers table already has ${count[0].n} rows, skipping seed.`);
}

console.log("Database ready.");

await pool.end();
