'use server';

import { db } from '@/lib/db';
import { registrations } from '@/lib/db/schema';
import { desc, eq } from 'drizzle-orm';

export type AdminRegistration = {
  id: string;
  fullName: string;
  email: string;
  phone: string;
  gender: string;
  ageRange: string;
  stack: string;
  motivation: string;
  heardFrom: string;
  referralCode: string | null;
  createdAt: Date;
};

export type DashboardStats = {
  total: number;
  byStack: Record<string, number>;
  byGender: Record<string, number>;
  byAgeRange: Record<string, number>;
  byHeardFrom: Record<string, number>;
  byReferral: Record<string, number>;
  recentCount: number;
};

export async function getRegistrations(): Promise<AdminRegistration[]> {
  const rows = await db
    .select()
    .from(registrations)
    .orderBy(desc(registrations.createdAt));

  return rows.map((r) => ({
    id: r.id,
    fullName: r.fullName,
    email: r.email,
    phone: r.phone,
    gender: r.gender,
    ageRange: r.ageRange,
    stack: r.stack,
    motivation: r.motivation,
    heardFrom: r.heardFrom,
    referralCode: r.referralCode ?? null,
    createdAt: r.createdAt,
  }));
}

export async function getDashboardStats(): Promise<DashboardStats> {
  const all = await db.select().from(registrations);

  const byStack: Record<string, number>     = {};
  const byGender: Record<string, number>    = {};
  const byAgeRange: Record<string, number>  = {};
  const byHeardFrom: Record<string, number> = {};
  const byReferral: Record<string, number>  = {};

  const sevenDaysAgo = new Date();
  sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
  let recentCount = 0;

  for (const r of all) {
    byStack[r.stack]       = (byStack[r.stack] || 0) + 1;
    byGender[r.gender]     = (byGender[r.gender] || 0) + 1;
    byAgeRange[r.ageRange] = (byAgeRange[r.ageRange] || 0) + 1;
    byHeardFrom[r.heardFrom] = (byHeardFrom[r.heardFrom] || 0) + 1;
    if (r.referralCode) {
      byReferral[r.referralCode] = (byReferral[r.referralCode] || 0) + 1;
    }
    if (r.createdAt >= sevenDaysAgo) recentCount++;
  }

  return {
    total: all.length,
    byStack,
    byGender,
    byAgeRange,
    byHeardFrom,
    byReferral,
    recentCount,
  };
}

export async function deleteRegistration(
  id: string
): Promise<{ success: boolean; error?: string }> {
  try {
    await db.delete(registrations).where(eq(registrations.id, id));
    return { success: true };
  } catch (err) {
    console.error('Delete error:', err);
    return { success: false, error: 'Failed to delete registration.' };
  }
}