// services/deleteRequestService.ts

export type DeleteStatus =
  | 'Delete Request With Supervisor'
  | 'Delete Request With CM'
  | 'Deleted'
  | ''
  | null
  | undefined;

export interface DeleteRequestResult {
  success: boolean;
  error?: string;
}

/**
 * Update the custom_delete_status field on any doctype
 */
export async function updateDeleteStatus(
  doctype: string,
  docname: string,
  status: DeleteStatus
): Promise<DeleteRequestResult> {
  try {
    const response = await fetch(`/api/resource/${doctype}/${encodeURIComponent(docname)}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ custom_delete_status: status }),
    });

    const result = await response.json();

    if (result.data || result.message) {
      return { success: true };
    }

    const errMsg =
      result.exc_type === 'ValidationError'
        ? result.exception || 'Validation error'
        : result._server_messages
        ? JSON.parse(result._server_messages)?.[0]?.message || 'Unknown error'
        : 'Failed to update delete status';

    return { success: false, error: errMsg };
  } catch (err) {
    return {
      success: false,
      error: err instanceof Error ? err.message : 'Network error',
    };
  }
}

/**
 * Fetch current delete status for a document
 */
export async function fetchDeleteStatus(
  doctype: string,
  docname: string
): Promise<DeleteStatus> {
  try {
    const response = await fetch(
      `/api/resource/${doctype}/${encodeURIComponent(docname)}?fields=["custom_delete_status"]`,
      { method: 'GET', credentials: 'include' }
    );
    const result = await response.json();
    return result?.data?.custom_delete_status ?? null;
  } catch {
    return null;
  }
}