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

export async function listTenants() {
  return db.select().from(tenants).orderBy(tenants.createdAt);
}

export async function listUsers() {
  return db.select().from(users).orderBy(users.createdAt);
}

export async function listPlans() {
  return db.select().from(plans).where(eq(plans.activo, true)).orderBy(plans.precioMensual);
}

export async function assignPlan(tenantId: string, planId: string) {
  await db.update(tenants).set({ planId }).where(eq(tenants.id, tenantId));
}

export async function setSubscriptionStatus(
  tenantId: string,
  status: (typeof tenants.subscriptionStatus.enumValues)[number]
) {
  await db.update(tenants).set({ subscriptionStatus: status }).where(eq(tenants.id, tenantId));
}

export async function setUserStatus(
  userId: string,
  status: (typeof users.status.enumValues)[number]
) {
  await db.update(users).set({ status, updatedAt: new Date() }).where(eq(users.id, userId));
}
