import 'server-only'

import { createAdminClient } from '@/lib/supabase/admin'
import type { SessionUser } from '@/lib/auth'
import type { BillingContext } from '@/lib/integrations/synchron-payments/types'
import type { Trip } from '@/types/db'

/**
 * Which billing customer a purchase is made for (task §22).
 *
 * A person can be a Carrier Dispatcher at Company A and a Freight Broker at
 * Company B. The purchase bills under the company of the ACTIVE mode
 * (SessionUser.contextKey → membership_roles) when that company is on the
 * trip, otherwise under the user alone. The Synchron tokens come from the
 * rows HHA already holds (profiles.source_token, companies.source_token);
 * the browser never supplies one.
 */

export type BillingResolution =
  | { ok: true; billing: BillingContext; companyId: string | null }
  | { ok: false; reason: 'not_authorized' }

export async function resolveBillingContext(user: SessionUser, trip: Trip): Promise<BillingResolution> {
  const admin = createAdminClient()

  const { data: profile } = await admin.from('profiles').select('id,source_token').eq('id', user.id).maybeSingle()
  const synchronUserToken = (profile as { source_token?: string | null } | null)?.source_token ?? null

  // Active mode → membership_roles row (SessionUser.contextKey is that row's
  // id, see src/lib/data/modes.ts loadUserContexts) → company. The active
  // mode wins; a single active role is the fallback; otherwise the trip's
  // carrier company if the user holds an active role there.
  let companyId: string | null = null
  const { data: roles } = await admin
    .from('membership_roles')
    .select('id,company_id,role_type,status')
    .eq('user_id', user.id)
    .eq('status', 'active')
  const active = (roles ?? []) as Array<{ id: string; company_id: string; role_type: string; status: string }>
  const tripCompany = trip.carrier_company_id ?? null
  const byContext = user.contextKey ? active.find((r) => r.id === user.contextKey) : undefined
  if (byContext) companyId = byContext.company_id
  else if (active.length === 1) companyId = active[0].company_id
  else if (tripCompany && active.some((r) => r.company_id === tripCompany)) companyId = tripCompany

  let synchronCarrierToken: string | null = null
  if (companyId) {
    const { data: company } = await admin.from('companies').select('source_token').eq('id', companyId).maybeSingle()
    synchronCarrierToken = (company as { source_token?: string | null } | null)?.source_token ?? null
  }

  return {
    ok: true,
    companyId,
    billing: {
      hhaUserId: user.id,
      hhaCompanyId: companyId,
      synchronUserToken,
      synchronCarrierToken,
      synchronOrderToken: trip.synchron_order_token ?? null,
      hhaTripId: trip.id,
    },
  }
}

/**
 * May this user READ a purchase? Owner, admin, or an approved billing-capable
 * member of the purchase's company (task §23).
 */
export async function canViewPurchase(user: SessionUser, purchase: { hha_user_id: string; company_id: string | null }): Promise<boolean> {
  if (user.role === 'admin' || purchase.hha_user_id === user.id) return true
  if (!purchase.company_id) return false
  const { data } = await createAdminClient()
    .from('company_memberships')
    .select('role,status')
    .eq('user_id', user.id)
    .eq('company_id', purchase.company_id)
    .eq('status', 'approved')
    .maybeSingle()
  const role = (data as { role?: string } | null)?.role
  return role === 'company_owner' || role === 'company_admin' || role === 'billing_admin'
}
