import apiClient from "@/lib/api/client";
import type { ApiResponse, QueryParams } from "@/lib/api/types";
import type { VolunteerOpportunityRoleRecord } from "@/features/opportunities/rolesAndTeamsRecord";

export const getRolesOfOpportunity = (
  params?: QueryParams
): Promise<ApiResponse<VolunteerOpportunityRoleRecord[]>> =>
  apiClient.get("/volunteer-opportunity-roles/", { params }).then((r) => r.data);

/**
 * `VolunteerOpportunityRoleController::store()`.
 *
 * The id key is **`opportunity_id`** on the write side, while the *read* side
 * of a learn-serve time slot calls the same thing `opportunity` — see
 * `LearnServeTimeSlotRecord`. Both names are real; neither is a typo.
 *
 * Both role names are `required` — a role cannot be created in one language
 * only, even though the read side types them as nullable (older rows and the
 * admin panel can produce a null). `max:100` on each.
 *
 * `participants_needed` is `min:1`: a role for nobody is a 422, which is why
 * the editor's shortfall arithmetic has to stop at zero rather than go
 * negative.
 */
export interface CreateVolunteerRoleBody {
  opportunity_id: number;
  /** `max:100`, required in both languages. */
  role_name_en: string;
  /** `max:100`, required in both languages. */
  role_name_ar: string;
  instructions_en?: string | null;
  instructions_ar?: string | null;
  /** `min:1`. */
  participants_needed: number;
}

/**
 * `update()` accepts the same keys minus `opportunity_id` — a role cannot be
 * moved between opportunities — with the two names and the count as
 * `sometimes`.
 */
export type UpdateVolunteerRoleBody = Partial<
  Omit<CreateVolunteerRoleBody, "opportunity_id">
>;

/* 201, with the created role in the detail shape. */
export const createVolunteerOpportunityRole = (
  data: CreateVolunteerRoleBody
): Promise<ApiResponse<VolunteerOpportunityRoleRecord>> =>
  apiClient.post("/volunteer-opportunity-roles/", data).then((r) => r.data);

export const getVolunteerOpportunityRoleById = (
  id: string
): Promise<ApiResponse<VolunteerOpportunityRoleRecord>> =>
  apiClient.get(`/volunteer-opportunity-roles/${id}/`).then((r) => r.data);

export const updateVolunteerOpportunityRole = ({
  id,
  data,
}: {
  id: string;
  data: UpdateVolunteerRoleBody;
}): Promise<ApiResponse<VolunteerOpportunityRoleRecord>> =>
  apiClient.patch(`/volunteer-opportunity-roles/${id}/`, data).then((r) => r.data);

export const deleteVolunteerOpportunityRole = (id: string): Promise<ApiResponse<null>> =>
  apiClient.delete(`/volunteer-opportunity-roles/${id}/`).then((r) => r.data);

export const deleteAllRoles = (opportunityId: number): Promise<ApiResponse<null>> =>
  apiClient.delete(`/delete-roles/${opportunityId}/`).then((r) => r.data);
