import { apiClient } from './client';
import type { LabCaseComment, LabTaskListItem } from '@/types/cases';

export interface LabCaseAccessProsthesisGroup {
  prosthesisTypeCode: string;
  prosthesisTypeLabel: string;
  teeth: string[];
  connected?: boolean;
  selectionGroupId?: string;
}

export interface LabCaseAccessSession {
  labCaseId: string;
  accessMode: 'lab' | 'clinic';
  canEditTaskStatus: boolean;
  canPostComments: boolean;
  canToggleCommentVisibility: boolean;
  shareUrl: string;
  sentAt: string | null;
  dueDate: string | null;
  isOverdue: boolean;
  isImportant: boolean;
  clinic: { id: string; name: string };
  lab: { id: string; name: string } | null;
  patient: { id: string; firstName: string; lastName: string };
  prosthesisGroups: LabCaseAccessProsthesisGroup[];
}

export const labCaseAccessApi = {
  resolve: async (
    token: string,
  ): Promise<{ success: boolean; data: LabCaseAccessSession }> => {
    const response = await apiClient.get(`/lab-cases/access/${encodeURIComponent(token)}`);
    return response.data;
  },

  listTasks: async (
    token: string,
  ): Promise<{ success: boolean; data: { items: LabTaskListItem[] } }> => {
    const response = await apiClient.get(
      `/lab-cases/access/${encodeURIComponent(token)}/tasks`,
    );
    return response.data;
  },

  listComments: async (
    token: string,
  ): Promise<{ success: boolean; data: LabCaseComment[] }> => {
    const response = await apiClient.get(
      `/lab-cases/access/${encodeURIComponent(token)}/comments`,
    );
    return response.data;
  },

  addComment: async (
    token: string,
    payload: { body: string; visibleToClinic?: boolean },
  ): Promise<{ success: boolean; data: LabCaseComment }> => {
    const response = await apiClient.post(
      `/lab-cases/access/${encodeURIComponent(token)}/comments`,
      payload,
    );
    return response.data;
  },

  setCommentVisibility: async (
    token: string,
    commentId: string,
    visibleToClinic: boolean,
  ): Promise<{ success: boolean; data: LabCaseComment }> => {
    const response = await apiClient.patch(
      `/lab-cases/access/${encodeURIComponent(token)}/comments/${commentId}/visibility`,
      { visibleToClinic },
    );
    return response.data;
  },
};
