export type AdminRole = {
  id: string
  name: string
  description?: string | null
  tenant_id: number | null
}

export type AdminTenant = {
  id: number
  name: string
  short: string
  user_count: number
  locked?: string | null
}

export type AdminUserProfile = {
  id: string
  user_id: string | null
  tenant_id: number
  full_name: string | null
  first_name: string
  last_name: string
  email?: string | null
  active: boolean
}

export type AdminUser = {
  id: string
  email: string
  display_name: string
  multiTenant: boolean
  must_change_password: boolean
  is_admin: boolean
  profile_defaults: {
    first_name: string
    last_name: string
  }
  tenant_ids: number[]
  role_assignments: { tenant_id: number; role_id: string }[]
  profile_assignments?: { tenant_id: number; profile_id?: string | null }[]
  profiles: AdminUserProfile[]
}

export type AdminOverview = {
  users: AdminUser[]
  tenants: AdminTenant[]
  roles: AdminRole[]
  unassignedProfiles: AdminUserProfile[]
}

export const useAdmin = () => {
  const { $api } = useNuxtApp()

  const getOverview = async (): Promise<AdminOverview> => {
    const response = await $api("/api/admin/overview")

    return {
      users: response?.users || [],
      tenants: response?.tenants || [],
      roles: response?.roles || [],
      unassignedProfiles: response?.unassignedProfiles || [],
    }
  }

  const createUser = async (body: Record<string, any>) => {
    return await $api("/api/admin/users", {
      method: "POST",
      body,
    })
  }

  const updateUser = async (id: string, body: Record<string, any>) => {
    return await $api(`/api/admin/users/${id}`, {
      method: "PUT",
      body,
    })
  }

  const updateUserAccess = async (id: string, body: Record<string, any>) => {
    return await $api(`/api/admin/users/${id}/access`, {
      method: "PUT",
      body,
    })
  }

  const createTenant = async (body: Record<string, any>) => {
    return await $api("/api/admin/tenants", {
      method: "POST",
      body,
    })
  }

  const updateTenant = async (id: number, body: Record<string, any>) => {
    return await $api(`/api/admin/tenants/${id}`, {
      method: "PUT",
      body,
    })
  }

  return {
    getOverview,
    createUser,
    updateUser,
    updateUserAccess,
    createTenant,
    updateTenant,
  }
}
