/**
 * Dev-only helper: create (or upsert) a CRM better-auth user and mark them
 * super_admin. Idempotent — re-running with the same email will reset the
 * password.
 *
 * Run: pnpm tsx scripts/dev-create-crm-user.ts <email> <password> [displayName]
 */

import 'dotenv/config';

import postgres from 'postgres';

import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { userProfiles } from '@/lib/db/schema/users';
import { env } from '@/lib/env';
import { eq } from 'drizzle-orm';

async function main() {
  const [email, password, displayNameArg] = process.argv.slice(2);
  if (!email || !password) {
    console.error(
      'Usage: pnpm tsx scripts/dev-create-crm-user.ts <email> <password> [displayName]',
    );
    process.exit(1);
  }

  const displayName = displayNameArg ?? email.split('@')[0] ?? 'User';
  const sql = postgres(env.DATABASE_URL);

  try {
    // 1. Check if better-auth user already exists.
    const existing = await sql<{ id: string }[]>`
      SELECT id FROM "user" WHERE email = ${email} LIMIT 1
    `;

    let userId: string;

    if (existing.length > 0) {
      const row = existing[0];
      if (!row) throw new Error('unreachable');
      userId = row.id;
      console.log(`User ${email} exists (id=${userId}); resetting password.`);
      // Use better-auth's internal context to hash and update the credential.
      const ctx = await auth.$context;
      const hash = await ctx.password.hash(password);
      await sql`
        UPDATE account
        SET password = ${hash}, updated_at = NOW()
        WHERE user_id = ${userId} AND provider_id = 'credential'
      `;
    } else {
      console.log(`Creating better-auth user ${email}…`);
      const result = await auth.api.signUpEmail({
        body: { email, password, name: displayName },
      });
      userId = result.user.id;
      console.log(`Created user_id=${userId}`);
    }

    // 2. Upsert user_profiles entry as super admin.
    const profile = await db
      .select()
      .from(userProfiles)
      .where(eq(userProfiles.userId, userId))
      .limit(1);

    if (profile.length === 0) {
      await db.insert(userProfiles).values({
        id: crypto.randomUUID(),
        userId,
        displayName,
        avatarUrl: null,
        phone: null,
        isSuperAdmin: true,
        isActive: true,
        lastLoginAt: null,
        preferences: {},
      });
      console.log(`Created super_admin profile for ${userId}`);
    } else {
      await db
        .update(userProfiles)
        .set({ displayName, isSuperAdmin: true, isActive: true })
        .where(eq(userProfiles.userId, userId));
      console.log(`Updated profile for ${userId} (super_admin=true)`);
    }

    console.log('');
    console.log(`✓ Done. Sign in at http://localhost:3000/login with`);
    console.log(`  email:    ${email}`);
    console.log(`  password: ${password}`);
  } finally {
    await sql.end();
    process.exit(0);
  }
}

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