import { getCsrfToken } from '@shared/api/csrf'
import { tokenStore } from '@shared/api/tokenStore'

const USERS_API_URL = 'https://app.users.elcsa.ru'

export type AccountType = 'individual' | 'legal_entity'

// Nested organization payload — present only on legal_entity accounts.
export interface LegalEntityInfo {
  id: string
  name: string
  inn: string
  status: string
  short_name: string | null
  ogrn: string | null
  kpp: string | null
  legal_address: string | null
  actual_address: string | null
  bank_details: Record<string, unknown> | null
  contact_person: string | null
  contact_phone: string | null
  kyc_verified: boolean
  kyc_verified_at: string | null
}

export interface MeResponse {
  id: string
  email: string
  // Person fields are null on legal_entity accounts.
  first_name: string | null
  middle_name: string | null
  last_name: string | null
  birth_date: string | null
  encrypted_mnemonic: string | null
  phone: string | null
  passport_data: string | null
  inn: string | null
  erc20: string | null
  avatar_link: string | null
  kyc_verified: boolean
  is_deleted: boolean
  created_at: string
  updated_at: string
  kyc_verified_at: string | null
  webp_size_bytes?: number
  // "individual" -> физлицо, "legal_entity" -> аккаунт юр.лица.
  account_type: AccountType
  // Populated only for legal_entity accounts.
  legal_entity?: LegalEntityInfo | null
}

export interface UploadAvatarPayload {
  photo_base64: string
  decoded_bytes: string
}

async function authedHeaders(): Promise<HeadersInit> {
  const csrf = await getCsrfToken()
  const bearer = tokenStore.get()
  return {
    'X-CSRF-Token': csrf,
    ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}),
  }
}

export async function getMe(): Promise<MeResponse> {
  const headers = await authedHeaders()

  const res = await fetch(`${USERS_API_URL}/me/`, {
    credentials: 'include',
    headers,
  })

  const data = await res.json()
  if (!res.ok) throw data
  return data
}

export async function uploadAvatar(payload: UploadAvatarPayload): Promise<MeResponse> {
  const headers = await authedHeaders()

  const res = await fetch(`${USERS_API_URL}/me/settings/avatar`, {
    method: 'PATCH',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      ...headers,
    },
    body: JSON.stringify(payload),
  })

  const data = await res.json()
  if (!res.ok) throw data
  return data
}

export interface PasswordResetStartPayload {
  email: string
}

export async function passwordResetStart(payload: PasswordResetStartPayload): Promise<void> {
  const csrf = await getCsrfToken()
  const res = await fetch(`${USERS_API_URL}/me/settings/password/forgot/start`, {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-Token': csrf,
    },
    body: JSON.stringify(payload),
  })
  if (!res.ok) {
    const data = await res.json().catch(() => ({}))
    throw data
  }
}

export async function updatePhone(phone: string): Promise<void> {
  const headers = await authedHeaders()

  const res = await fetch(`${USERS_API_URL}/me/settings/phone`, {
    method: 'PATCH',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      ...headers,
    },
    body: JSON.stringify({ phone }),
  })

  if (!res.ok) {
    const data = await res.json().catch(() => ({}))
    throw data
  }
}

export interface PasswordResetCompletePayload {
  email: string
  code: string
  new_password: string
  confirm_password: string
}

export async function passwordResetComplete(payload: PasswordResetCompletePayload): Promise<void> {
  const csrf = await getCsrfToken()
  const res = await fetch(`${USERS_API_URL}/me/settings/password/forgot/complete`, {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-Token': csrf,
    },
    body: JSON.stringify(payload),
  })
  if (!res.ok) {
    const data = await res.json().catch(() => ({}))
    throw data
  }
}
