import { randomUUID } from "node:crypto";
import { hashPassword } from "@/server/auth/password";
import { db } from "@/server/db";

export const TEST_PASSWORD = "Prueba-segura-2026";

/** Crea un usuario de prueba con email único. */
export async function createTestUser(
  roleKey: "SUPER_ADMIN" | "ADMIN" | "SUPERVISOR" | "ADVISOR",
  overrides: { isActive?: boolean; mustChangePassword?: boolean } = {},
) {
  const role = await db.role.findUniqueOrThrow({ where: { key: roleKey } });
  return db.user.create({
    data: {
      email: `test-${randomUUID()}@test.chesco.local`,
      name: `Test ${roleKey}`,
      roleId: role.id,
      passwordHash: await hashPassword(TEST_PASSWORD),
      isActive: overrides.isActive ?? true,
      mustChangePassword: overrides.mustChangePassword ?? false,
    },
  });
}

/** Marca, modelo, vehículo y cliente mínimos para probar ventas y reservas. */
export async function createSaleFixtures() {
  const suffix = randomUUID().slice(0, 8);
  const brand = await db.brand.create({
    data: { name: `Marca ${suffix}`, slug: `marca-${suffix}` },
  });
  const model = await db.vehicleModel.create({
    data: { brandId: brand.id, name: `Modelo ${suffix}`, slug: `modelo-${suffix}` },
  });
  const vehicle = await db.vehicle.create({
    data: {
      code: `TEST-${suffix}`,
      slug: `test-${suffix}`,
      brandId: brand.id,
      modelId: model.id,
      year: 2024,
      price: "20000",
      currency: "USD",
      mileageKm: 1000,
      transmission: "AUTOMATIC",
      fuelType: "GASOLINE",
      bodyType: "SUV",
      status: "AVAILABLE",
      isDemo: true,
    },
  });
  const customer = await db.customer.create({ data: { firstName: "Cliente", lastName: "Prueba" } });
  const advisor = await createTestUser("ADVISOR");
  return { brand, model, vehicle, customer, advisor };
}
