import { prisma } from '../../config/database';
import { AppError } from '../../middleware/error-handler';
import {
  volunteerDashboardService,
  type VolunteerDashboardPayload,
} from '../volunteer-dashboard/volunteer-dashboard.service';
import type { BridgeVolunteerDashboardInput } from './volunteer-bridge.schemas';

export const volunteerBridgeService = {
  async getDashboardByEmail(
    input: BridgeVolunteerDashboardInput,
  ): Promise<VolunteerDashboardPayload> {
    const email = input.email.trim().toLowerCase();
    const user = await prisma.user.findUnique({
      where: { email },
      select: { id: true },
    });
    if (!user) {
      throw new AppError(404, 'No cmlite user for this email', 'NO_CMLITE_USER');
    }
    const dash = await volunteerDashboardService.getDashboard(user.id);
    if (!dash) {
      // getDashboard returns null only if profile lookup fails — same effect
      // as user-not-found for our purposes, but distinct code to aid debug.
      throw new AppError(404, 'Dashboard could not be assembled', 'DASHBOARD_UNAVAILABLE');
    }
    return dash;
  },
};
