import { apiRequest } from '@/shared/api/httpClient';
import { ApiListResponse } from '@/shared/types/api';
import type {
  CampusAttendanceCampusKey,
  CampusAttendanceConfigDto,
  CampusAttendanceConfigMutationDto,
  CampusAttendanceListFilter,
  CampusAttendanceSummaryDto,
  CampusAttendanceSummaryMutationDto,
} from '@/shared/types/campusAttendance';

const CAMPUS_ATTENDANCE_PATH = '/campus_attendance';

function toSearchParams(filter?: CampusAttendanceListFilter): string {
  if (!filter) {
    return '';
  }

  const params = new URLSearchParams();

  if (filter.campusKey) {
    params.set('campusKey', filter.campusKey);
  }

  if (filter.startDate) {
    params.set('startDate', filter.startDate);
  }

  if (filter.endDate) {
    params.set('endDate', filter.endDate);
  }

  if (filter.limit) {
    params.set('limit', String(filter.limit));
  }

  const query = params.toString();
  return query ? `?${query}` : '';
}

export function listCampusAttendanceConfigs(
  filter?: Pick<CampusAttendanceListFilter, 'campusKey'>,
): Promise<ApiListResponse<CampusAttendanceConfigDto>> {
  return apiRequest<ApiListResponse<CampusAttendanceConfigDto>>(
    `${CAMPUS_ATTENDANCE_PATH}/configs${toSearchParams(filter)}`,
  );
}

export function saveCampusAttendanceConfig(
  campusKey: CampusAttendanceCampusKey,
  request: CampusAttendanceConfigMutationDto,
): Promise<CampusAttendanceConfigDto> {
  return apiRequest<CampusAttendanceConfigDto>(`${CAMPUS_ATTENDANCE_PATH}/configs/${campusKey}`, {
    method: 'PUT',
    body: { data: request },
  });
}

export function listCampusAttendanceSummaries(
  filter?: CampusAttendanceListFilter,
): Promise<ApiListResponse<CampusAttendanceSummaryDto>> {
  return apiRequest<ApiListResponse<CampusAttendanceSummaryDto>>(
    `${CAMPUS_ATTENDANCE_PATH}/summaries${toSearchParams(filter)}`,
  );
}

export function saveCampusAttendanceSummary(
  campusKey: CampusAttendanceCampusKey,
  date: string,
  request: CampusAttendanceSummaryMutationDto,
): Promise<CampusAttendanceSummaryDto> {
  return apiRequest<CampusAttendanceSummaryDto>(`${CAMPUS_ATTENDANCE_PATH}/summaries/${campusKey}/${date}`, {
    method: 'PUT',
    body: { data: request },
  });
}
