import apiClient from './client';

export interface Family {
  id: string;
  name: string;
  shareCode: string;
  createdBy: string;
  subscriptionTier: string;
  members?: FamilyMember[];
}

export interface FamilyMember {
  id: string;
  userId: string;
  familyId: string;
  role: 'parent' | 'caregiver' | 'viewer';
  permissions: any;
  user?: {
    id: string;
    name: string;
    email: string;
  };
}

export interface InviteMemberData {
  email: string;
  role: 'parent' | 'caregiver' | 'viewer';
}

export interface JoinFamilyData {
  shareCode: string;
}

export const familiesApi = {
  // Get a specific family
  getFamily: async (familyId: string): Promise<Family> => {
    const response = await apiClient.get(`/api/v1/families/${familyId}`);
    return response.data.data.family;
  },

  // Get family members
  getFamilyMembers: async (familyId: string): Promise<FamilyMember[]> => {
    const response = await apiClient.get(`/api/v1/families/${familyId}/members`);
    return response.data.data.members;
  },

  // Invite a family member
  inviteMember: async (familyId: string, data: InviteMemberData): Promise<any> => {
    const response = await apiClient.post(`/api/v1/families/invite?familyId=${familyId}`, data);
    return response.data.data.invitation;
  },

  // Join a family using share code
  joinFamily: async (data: JoinFamilyData): Promise<FamilyMember> => {
    const response = await apiClient.post('/api/v1/families/join', data);
    return response.data.data.member;
  },

  // Update member role
  updateMemberRole: async (familyId: string, userId: string, role: string): Promise<FamilyMember> => {
    const response = await apiClient.patch(`/api/v1/families/${familyId}/members/${userId}/role`, { role });
    return response.data.data.member;
  },

  // Remove a family member
  removeMember: async (familyId: string, userId: string): Promise<void> => {
    await apiClient.delete(`/api/v1/families/${familyId}/members/${userId}`);
  },
};
