import { PureAbility } from '@casl/ability';
import { createClient } from '@/lib/supabase/server';
import { defineAbilityFor, type AppAbility, type AppAction, type AppSubject, type PagePermissions } from './ability';

/**
 * Build an ability instance on the server side for use in server actions/API routes.
 * Fetches the user's role and permissions from the database.
 * 
 * This file must only be imported from server components or server actions.
 */
export async function getServerAbility(): Promise<AppAbility> {
  const supabase = await createClient();

  const { data: { user } } = await supabase.auth.getUser();
  if (!user) {
    return new PureAbility<[AppAction, AppSubject]>();
  }

  // Get the user's role
  const { data: profile } = await supabase
    .from('users')
    .select('role')
    .eq('id', user.id)
    .single();

  const role = profile?.role || 'user';
  const normalizedRole = role.toLowerCase();

  // Admins and developers already get 'manage all' — skip the DB query
  if (normalizedRole === 'admin' || normalizedRole === 'developer') {
    return defineAbilityFor(role, {});
  }

  // Fetch role-specific permissions from the database
  const { data: rolePermissions } = await supabase
    .from('role_permissions')
    .select('page, permissions')
    .eq('role_name', role);

  const pagePermissions: PagePermissions = {};
  if (rolePermissions) {
    for (const row of rolePermissions) {
      pagePermissions[row.page] = row.permissions as ('view' | 'create' | 'edit' | 'delete')[];
    }
  }

  return defineAbilityFor(role, pagePermissions);
}
