'use client'

import { useMemo } from 'react'
import { useCompliance } from './hooks-core'
import type { ConsentPurpose } from '@breakpilot/compliance-sdk-types'

// =============================================================================
// DSGVO HOOKS
// =============================================================================

export function useDSGVO() {
  const { dsgvo, state } = useCompliance()

  return useMemo(
    () => ({
      // DSR
      dsrRequests: state.dsrRequests,
      dsrConfig: state.dsrConfig,
      submitDSR: dsgvo.submitDSR.bind(dsgvo),

      // Consent
      consents: state.consents,
      hasConsent: dsgvo.hasConsent.bind(dsgvo),
      getConsentsByUserId: dsgvo.getConsentsByUserId.bind(dsgvo),

      // VVT
      processingActivities: state.vvt,
      getProcessingActivityById: dsgvo.getProcessingActivityById.bind(dsgvo),

      // DSFA
      dsfa: state.dsfa,
      isDSFARequired: dsgvo.isDSFARequired.bind(dsgvo),

      // TOMs
      toms: state.toms,
      getTOMsByCategory: dsgvo.getTOMsByCategory.bind(dsgvo),
      getTOMScore: dsgvo.getTOMScore.bind(dsgvo),

      // Retention
      retentionPolicies: state.retentionPolicies,
      getUpcomingDeletions: dsgvo.getUpcomingDeletions.bind(dsgvo),

      // Cookie Banner
      cookieBanner: state.cookieBanner,
      generateCookieBannerCode: dsgvo.generateCookieBannerCode.bind(dsgvo),
    }),
    [dsgvo, state]
  )
}

export function useConsent(userId: string) {
  const { dsgvo, state } = useCompliance()

  return useMemo(() => {
    const userConsents = state.consents.filter(c => c.userId === userId)

    return {
      consents: userConsents,
      hasConsent: (purpose: ConsentPurpose) => dsgvo.hasConsent(userId, purpose),
      hasAnalyticsConsent: dsgvo.hasConsent(userId, 'ANALYTICS'),
      hasMarketingConsent: dsgvo.hasConsent(userId, 'MARKETING'),
      hasFunctionalConsent: dsgvo.hasConsent(userId, 'FUNCTIONAL'),
    }
  }, [dsgvo, state.consents, userId])
}

export function useDSR() {
  const { dsgvo, state } = useCompliance()

  return useMemo(
    () => ({
      requests: state.dsrRequests,
      config: state.dsrConfig,
      submitRequest: dsgvo.submitDSR.bind(dsgvo),
      pendingRequests: state.dsrRequests.filter(r => r.status !== 'COMPLETED' && r.status !== 'REJECTED'),
      overdueRequests: state.dsrRequests.filter(r => {
        if (r.status === 'COMPLETED' || r.status === 'REJECTED') return false
        return new Date(r.dueDate) < new Date()
      }),
    }),
    [dsgvo, state.dsrRequests, state.dsrConfig]
  )
}
