'use client'

import { useContext, useMemo, createContext } from 'react'
import { VendorComplianceContextValue } from './types'

// ==========================================
// CONTEXT
// ==========================================

export const VendorComplianceContext = createContext<VendorComplianceContextValue | null>(null)

// ==========================================
// HOOK
// ==========================================

export function useVendorCompliance(): VendorComplianceContextValue {
  const context = useContext(VendorComplianceContext)

  if (!context) {
    throw new Error(
      'useVendorCompliance must be used within a VendorComplianceProvider'
    )
  }

  return context
}

// ==========================================
// SELECTORS
// ==========================================

export function useVendor(vendorId: string | null) {
  const { vendors } = useVendorCompliance()
  return useMemo(
    () => vendors.find((v) => v.id === vendorId) ?? null,
    [vendors, vendorId]
  )
}

export function useProcessingActivity(activityId: string | null) {
  const { processingActivities } = useVendorCompliance()
  return useMemo(
    () => processingActivities.find((a) => a.id === activityId) ?? null,
    [processingActivities, activityId]
  )
}

export function useVendorContracts(vendorId: string | null) {
  const { contracts } = useVendorCompliance()
  return useMemo(
    () => contracts.filter((c) => c.vendorId === vendorId),
    [contracts, vendorId]
  )
}

export function useVendorFindings(vendorId: string | null) {
  const { findings } = useVendorCompliance()
  return useMemo(
    () => findings.filter((f) => f.vendorId === vendorId),
    [findings, vendorId]
  )
}

export function useContractFindings(contractId: string | null) {
  const { findings } = useVendorCompliance()
  return useMemo(
    () => findings.filter((f) => f.contractId === contractId),
    [findings, contractId]
  )
}

export function useControlInstancesForEntity(
  entityType: 'VENDOR' | 'PROCESSING_ACTIVITY',
  entityId: string | null
) {
  const { controlInstances, controls } = useVendorCompliance()

  return useMemo(() => {
    if (!entityId) return []

    return controlInstances
      .filter((ci) => ci.entityType === entityType && ci.entityId === entityId)
      .map((ci) => ({
        ...ci,
        control: controls.find((c) => c.id === ci.controlId),
      }))
  }, [controlInstances, controls, entityType, entityId])
}
