import apiClient from './client'
import type { Account, SubscriptionDetails, AccountMember, AccountInvite } from '@/types'

export const accountsApi = {
  async getMyAccount(): Promise<Account> {
    const response = await apiClient.get<Account>('/accounts/me')
    return response.data
  },

  async getMySubscription(): Promise<SubscriptionDetails> {
    const response = await apiClient.get<SubscriptionDetails>('/accounts/me/subscription')
    return response.data
  },

  async updateMyAccount(data: { name?: string }): Promise<Account> {
    const response = await apiClient.patch<Account>('/accounts/me', data)
    return response.data
  },

  async getMembers(): Promise<AccountMember[]> {
    const response = await apiClient.get<AccountMember[]>('/accounts/me/members')
    return response.data
  },

  async updateMemberRole(userId: string, role: string): Promise<AccountMember> {
    const response = await apiClient.patch<AccountMember>(
      `/accounts/me/members/${userId}/role`,
      { account_role: role }
    )
    return response.data
  },

  async removeMember(userId: string): Promise<void> {
    await apiClient.delete(`/accounts/me/members/${userId}`)
  },

  async createInvite(data: { email: string; role: string }): Promise<AccountInvite> {
    const response = await apiClient.post<AccountInvite>('/accounts/me/invites', data)
    return response.data
  },

  async getInvites(): Promise<AccountInvite[]> {
    const response = await apiClient.get<AccountInvite[]>('/accounts/me/invites')
    return response.data
  },

  async resendInvite(inviteId: string): Promise<AccountInvite> {
    const response = await apiClient.post<AccountInvite>(`/accounts/me/invites/${inviteId}/resend`)
    return response.data
  },

  async transferOwnership(currentPassword: string, targetUserId: string): Promise<Account> {
    const response = await apiClient.post<Account>('/accounts/me/transfer-ownership', {
      current_password: currentPassword,
      target_user_id: targetUserId,
    })
    return response.data
  },

  async leaveAccount(): Promise<void> {
    await apiClient.post('/accounts/me/leave')
  },

  async deleteAccount(currentPassword: string): Promise<void> {
    await apiClient.delete('/accounts/me', { data: { current_password: currentPassword } })
  },
}

export default accountsApi
