import axios from '@/network/axios';
import { apis } from '@/utils/apis/apis';
import type {
  CreatorVerification,
  CreatorVerificationStatus,
  CreatorVerificationsListResponse,
} from './creator-verifications.types';

const CV = apis.DASHBOARD.MARKETPLACE_ADMIN.CREATOR_VERIFICATIONS;

type SuccessResponse<T> = {
  status: boolean;
  message: string;
  data: T;
};

export type CreatorVerificationsListParams = {
  page?: number;
  per_page?: number;
  status?: string;
  search?: string;
};

/** Empty strings would be sent as `?status=` and read as a real filter. */
const clean = (params: Record<string, unknown>) =>
  Object.fromEntries(
    Object.entries(params).filter(
      ([, v]) => v !== '' && v !== null && v !== undefined,
    ),
  );

export const fetchCreatorVerifications = async (
  params: CreatorVerificationsListParams,
) => {
  const res = await axios.get<SuccessResponse<CreatorVerificationsListResponse>>(
    CV.LIST,
    { params: clean(params) },
  );
  return res.data?.data;
};

export const fetchCreatorVerification = async (id: number) => {
  const res = await axios.get<SuccessResponse<CreatorVerification>>(CV.SHOW(id));
  return res.data?.data;
};

export const approveCreatorVerification = async (id: number) => {
  const res = await axios.post<SuccessResponse<CreatorVerification>>(
    CV.APPROVE(id),
  );
  return res.data?.data;
};

/**
 * Set any status. `note` is required for needs_completion and rejected, and is
 * shown to the creator as what to fix or why.
 */
export const setCreatorVerificationStatus = async (
  id: number,
  status: CreatorVerificationStatus,
  note?: string,
) => {
  const res = await axios.post<SuccessResponse<CreatorVerification>>(
    CV.STATUS(id),
    { status, ...(note ? { note } : {}) },
  );
  return res.data?.data;
};

/**
 * A reason is required by the API, not optional — "rejected" on its own leaves
 * the creator to guess which field was wrong and resubmit blind.
 */
export const rejectCreatorVerification = async (
  id: number,
  rejection_reason: string,
) => {
  const res = await axios.post<SuccessResponse<CreatorVerification>>(
    CV.REJECT(id),
    { rejection_reason },
  );
  return res.data?.data;
};
