import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'

export type PhoneNumberType = 'landline' | 'cell'

export interface BusinessPhoneNumber {
  type: PhoneNumberType
  number: string
}

export interface BusinessSocialMedia {
  whatsapp: string
  telegram: string
  instagram: string
  linkedin: string
  youtube: string
  aparat: string
}

export interface BusinessProfile {
  nameEn: string
  nameFa: string
  about: string
  vision: string
  emails: string[]
  phoneNumbers: BusinessPhoneNumber[]
  socialMedia: BusinessSocialMedia
  logoMediaId: string | null
  logoUrl: string | null
  faviconMediaId: string | null
  faviconUrl: string | null
  categoryIds: string[]
}

export interface BusinessAddress {
  id: string
  province: string
  city: string
  address: string
  postalCode: string
  landline: string | null
}

export interface BusinessProfileResponse {
  businessId: string
  profile: BusinessProfile
  addresses: BusinessAddress[]
}

export interface UpdateBusinessProfilePayload {
  nameEn?: string
  nameFa?: string
  about?: string
  vision?: string
  emails?: string[]
  phoneNumbers?: BusinessPhoneNumber[]
  socialMedia?: Partial<BusinessSocialMedia>
  logoMediaId?: string | null
  categoryIds?: string[]
  addresses?: Array<{
    id?: string
    province: string
    city: string
    address: string
    postalCode: string
    landline?: string | null
  }>
}

function profilePath() {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/profile`
}

export async function getBusinessProfile(signal?: AbortSignal) {
  return apiRequest<BusinessProfileResponse>(profilePath(), { auth: true, signal })
}

export async function updateBusinessProfile(payload: UpdateBusinessProfilePayload) {
  return apiRequest<BusinessProfileResponse>(profilePath(), {
    method: 'PATCH',
    auth: true,
    body: {
      ...payload,
      categoryIds: payload.categoryIds?.map((id) => Number(id)),
      logoMediaId:
        payload.logoMediaId === undefined
          ? undefined
          : payload.logoMediaId
            ? Number(payload.logoMediaId)
            : null,
    },
  })
}
