import { api } from "@/lib/api/client";

export type AttendanceRecord = {
	id: string;
	employeeId: string;
	employeeCode: string;
	employeeName: string;
	workDate: string;
	firstIn: string | null;
	lastOut: string | null;
	totalWorkMinutes: number;
	punchCount: number;
	status: "present" | "incomplete";
	shiftName: string | null;
	shiftStartTime: string | null;
	graceTimeIn: number | null;
	isLate: boolean;
	lateMinutes: number;
	lateArrivalStatus: "pending" | "approved" | "rejected" | "cancelled" | null;
	isLateExcused: boolean;
};

export type AttendancePunch = {
	id: string;
	employeeId: string | null;
	employeeCode: string;
	employeeName: string | null;
	punchedAt: string;
	punchType: string;
	verifyMode: string;
	source: string;
	deviceId: string;
	deviceName: string | null;
	deviceSerial: string;
	isMapped: boolean;
};

export type LivePunch = {
	punchId: string;
	employeeId: string | null;
	employeeCode: string;
	employeeName: string | null;
	punchedAt: string;
	punchType: string;
	deviceName: string | null;
	deviceSerial: string;
	workDate: string;
	isMapped: boolean;
};

export function getAttendanceRecords(params: {
	month?: string;
	date?: string;
	employeeId?: string;
}) {
	const search = new URLSearchParams();
	if (params.month) search.set("month", params.month);
	if (params.date) search.set("date", params.date);
	if (params.employeeId) search.set("employeeId", params.employeeId);
	const query = search.toString();
	return api.get<{ items: AttendanceRecord[] }>(
		`/attendance/records${query ? `?${query}` : ""}`,
	);
}

export function getAttendancePunches(params: {
	date?: string;
	employeeId?: string;
	limit?: number;
}) {
	const search = new URLSearchParams();
	if (params.date) search.set("date", params.date);
	if (params.employeeId) search.set("employeeId", params.employeeId);
	if (params.limit) search.set("limit", String(params.limit));
	const query = search.toString();
	return api.get<{ total: number; items: AttendancePunch[] }>(
		`/attendance/punches${query ? `?${query}` : ""}`,
	);
}

export function getLiveAttendance(
	limit = 20,
	params: { date?: string; all?: boolean; deviceId?: string } = {},
) {
	const search = new URLSearchParams();
	search.set("limit", String(limit));
	if (params.date) search.set("date", params.date);
	if (params.all) search.set("all", "true");
	if (params.deviceId) search.set("deviceId", params.deviceId);
	return api.get<{
		scope: string;
		lastPunchAt: string | null;
		items: LivePunch[];
	}>(`/attendance/live?${search.toString()}`);
}

export type MachineCsvImportResult = {
	file: string;
	parsed: number;
	imported: number;
	skipped: number;
	employeesCreated: number;
	punchesRemapped: number;
	recordsRebuilt: number;
};

export function importMachineCsv(file?: string) {
	const search = new URLSearchParams();
	if (file) search.set("file", file);
	const query = search.toString();
	return api.post<MachineCsvImportResult>(
		`/attendance/import-machine-csv${query ? `?${query}` : ""}`,
	);
}
