"use server";

import { revalidateTag } from "next/cache";
import { attendanceService, dashboardService } from "@/services/dashboardService";
import { leaveService } from "@/services/leaveService";
import { getAuthHeaders } from "@/app/actions/config";
import { withServerAction } from "@/lib/server/server-action-wrapper";
import { CACHE_TAGS, DEFAULT_CACHE_PROFILE } from "./cache-tags";

export async function fetchDashboardDataAction(isHRAdmin: boolean) {
  return withServerAction(async () => {
    const headers = await getAuthHeaders();
    if (isHRAdmin) {
      const [allUsers, leaveRes] = await Promise.all([
        dashboardService.getAllUsers({ headers }),
        leaveService.getAllRequests({ limit: 100 }, { headers })
      ]);

      const allLeaves = leaveRes.data || [];

      return {
        stats: {
          totalEmployees: allUsers?.length || 0,
          presentToday: Math.floor((allUsers?.length || 0) * 0.85),
          pendingLeaves: allLeaves?.filter((l: any) => l.status === "PENDING").length || 0,
          biometricAlerts: 0
        },
        recentRequests: allLeaves.slice(0, 5)
      };
    } else {
      const [leaveRes, todayStatus] = await Promise.all([
        leaveService.getRequests({ limit: 5 }, { headers }),
        attendanceService.getToday({ headers })
      ]);
      return {
        recentRequests: leaveRes.data || [],
        todayAttendance: todayStatus?.[0] || null
      };
    }
  })
}

export async function attendanceAction(type: "checkIn" | "checkOut", method: string = "GPS") {
  try {
    const headers = await getAuthHeaders();
    const result = type === "checkIn"
      ? await attendanceService.checkIn(method, { headers })
      : await attendanceService.checkOut(method, { headers });

    revalidateTag(CACHE_TAGS.attendance, DEFAULT_CACHE_PROFILE);
    revalidateTag(CACHE_TAGS.dashboard, DEFAULT_CACHE_PROFILE);
    return { success: true, data: result };
  } catch (error: any) {
    // Return error gracefully instead of throwing
    // This prevents Next.js from logging expected validation errors
    const message = error?.response?.data?.message || error?.message || "Attendance action failed";
    return { success: false, error: message };
  }
}
