import { eq } from 'drizzle-orm';
import { db } from './index';
import { users, tenants } from './schema';

const TRIAL_MS = 14 * 24 * 60 * 60 * 1000;

export async function getUserByEmail(email: string) {
  const [row] = await db.select().from(users).where(eq(users.email, email)).limit(1);
  return row ?? null;
}

export async function getUserById(id: string) {
  const [row] = await db.select().from(users).where(eq(users.id, id)).limit(1);
  return row ?? null;
}

export async function createTenantWithOwner(input: {
  nombreEmpresa: string;
  slug: string;
  provincia: string | null;
  email: string;
  passwordHash: string;
  nombre: string | null;
}) {
  const [tenant] = await db
    .insert(tenants)
    .values({
      slug: input.slug,
      nombreEmpresa: input.nombreEmpresa,
      provincia: input.provincia,
      subscriptionStatus: 'trial',
      trialEndsAt: new Date(Date.now() + TRIAL_MS),
    })
    .returning();

  const [user] = await db
    .insert(users)
    .values({
      email: input.email,
      passwordHash: input.passwordHash,
      nombre: input.nombre,
      role: 'reformista',
      tenantId: tenant.id,
    })
    .returning();

  return { tenant, user };
}

export async function slugDisponible(slug: string): Promise<boolean> {
  const [row] = await db.select({ id: tenants.id }).from(tenants).where(eq(tenants.slug, slug)).limit(1);
  return !row;
}
