/**
 * Project Memberships Query Hooks
 *
 * React Query hooks for fetching project membership data.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { queryKeys } from '../../lib/queryClient';

interface ProjectMembership {
  id: string;
  projectId: string;
  userId: string;
  role: string;
  user?: {
    id: string;
    firstName: string;
    lastName: string;
    email: string;
  };
}

interface ProjectMembershipListResponse {
  rows: ProjectMembership[];
  count: number;
}

/**
 * Fetch list of memberships for a project
 */
export function useProjectMembershipsQuery(projectId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.projectMemberships.list(projectId || ''),
    queryFn: async (): Promise<ProjectMembership[]> => {
      const response = await axios.get<ProjectMembershipListResponse>(
        `project_memberships?projectId=${projectId}`,
      );
      return response.data.rows;
    },
    enabled: !!projectId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Create project membership mutation
 */
export function useCreateProjectMembershipMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (
      data: Partial<ProjectMembership>,
    ): Promise<ProjectMembership> => {
      const response = await axios.post<ProjectMembership>(
        'project_memberships',
        { data },
      );
      return response.data;
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: queryKeys.projectMemberships.list(variables.projectId || ''),
      });
    },
  });
}

/**
 * Delete project membership mutation
 */
export function useDeleteProjectMembershipMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      id,
      projectId,
    }: {
      id: string;
      projectId: string;
    }): Promise<void> => {
      await axios.delete(`project_memberships/${id}`);
    },
    onSuccess: (_, { projectId }) => {
      queryClient.invalidateQueries({
        queryKey: queryKeys.projectMemberships.list(projectId),
      });
    },
  });
}

export default useProjectMembershipsQuery;
