/**
 * DSGVO/GDPR composable
 */

import { computed, type ComputedRef, type Ref, ref } from 'vue'
import { useComplianceStore } from '../plugin'
import type {
  DSRRequest,
  DSRRequestType,
  ConsentRecord,
  ConsentPurpose,
  ProcessingActivity,
  TOM,
  TOMCategory,
  DSFA,
  RetentionPolicy,
} from '@breakpilot/compliance-sdk-types'

export interface UseDSGVOReturn {
  // DSR
  dsrRequests: ComputedRef<DSRRequest[]>
  pendingDSRCount: ComputedRef<number>
  submitDSR: (type: DSRRequestType, email: string, name: string) => Promise<DSRRequest>
  updateDSRStatus: (
    requestId: string,
    status: DSRRequest['status'],
    notes?: string
  ) => Promise<void>

  // Consent
  consents: ComputedRef<ConsentRecord[]>
  activeConsents: ComputedRef<ConsentRecord[]>
  hasConsent: (purpose: ConsentPurpose) => boolean
  recordConsent: (
    purpose: ConsentPurpose,
    granted: boolean,
    source: string
  ) => Promise<ConsentRecord>
  revokeConsent: (consentId: string) => Promise<void>

  // VVT (Processing Activities)
  processingActivities: ComputedRef<ProcessingActivity[]>
  addProcessingActivity: (activity: Omit<ProcessingActivity, 'id' | 'createdAt'>) => void
  updateProcessingActivity: (id: string, updates: Partial<ProcessingActivity>) => void
  deleteProcessingActivity: (id: string) => void

  // TOM
  toms: ComputedRef<TOM[]>
  tomsByCategory: ComputedRef<Record<TOMCategory, TOM[]>>
  addTOM: (tom: Omit<TOM, 'id' | 'createdAt' | 'updatedAt'>) => void
  updateTOM: (id: string, updates: Partial<TOM>) => void
  deleteTOM: (id: string) => void

  // DSFA
  dsfas: ComputedRef<DSFA[]>
  createDSFA: (title: string, description: string) => DSFA
  updateDSFA: (id: string, updates: Partial<DSFA>) => void

  // Retention
  retentionPolicies: ComputedRef<RetentionPolicy[]>
  addRetentionPolicy: (policy: Omit<RetentionPolicy, 'id'>) => void
  updateRetentionPolicy: (id: string, updates: Partial<RetentionPolicy>) => void
  deleteRetentionPolicy: (id: string) => void

  // Loading state
  isLoading: Ref<boolean>
}

export function useDSGVO(): UseDSGVOReturn {
  const store = useComplianceStore()
  const { state, dispatch, dsgvo } = store

  const isLoading = ref(false)

  // DSR
  const dsrRequests = computed(() => state.dsrRequests)

  const pendingDSRCount = computed(
    () => state.dsrRequests.filter(r => r.status === 'PENDING' || r.status === 'IN_PROGRESS').length
  )

  const submitDSR = async (
    type: DSRRequestType,
    email: string,
    name: string
  ): Promise<DSRRequest> => {
    isLoading.value = true
    try {
      return await dsgvo.submitDSR(type, email, name)
    } finally {
      isLoading.value = false
    }
  }

  const updateDSRStatus = async (
    requestId: string,
    status: DSRRequest['status'],
    notes?: string
  ): Promise<void> => {
    isLoading.value = true
    try {
      await dsgvo.updateDSRStatus(requestId, status, notes)
    } finally {
      isLoading.value = false
    }
  }

  // Consent
  const consents = computed(() => state.consents)

  const activeConsents = computed(() =>
    state.consents.filter(c => c.status === 'ACTIVE' && !c.revokedAt)
  )

  const hasConsent = (purpose: ConsentPurpose): boolean => {
    return dsgvo.hasActiveConsent(purpose)
  }

  const recordConsent = async (
    purpose: ConsentPurpose,
    granted: boolean,
    source: string
  ): Promise<ConsentRecord> => {
    isLoading.value = true
    try {
      return await dsgvo.recordConsent(purpose, granted, source)
    } finally {
      isLoading.value = false
    }
  }

  const revokeConsent = async (consentId: string): Promise<void> => {
    isLoading.value = true
    try {
      await dsgvo.revokeConsent(consentId)
    } finally {
      isLoading.value = false
    }
  }

  // VVT
  const processingActivities = computed(() => state.processingActivities)

  const addProcessingActivity = (activity: Omit<ProcessingActivity, 'id' | 'createdAt'>): void => {
    dispatch({ type: 'ADD_PROCESSING_ACTIVITY', payload: activity })
  }

  const updateProcessingActivity = (id: string, updates: Partial<ProcessingActivity>): void => {
    dispatch({ type: 'UPDATE_PROCESSING_ACTIVITY', payload: { id, updates } })
  }

  const deleteProcessingActivity = (id: string): void => {
    dispatch({ type: 'DELETE_PROCESSING_ACTIVITY', payload: id })
  }

  // TOM
  const toms = computed(() => state.toms)

  const tomsByCategory = computed(() => {
    const categories: TOMCategory[] = [
      'ZUTRITTSKONTROLLE',
      'ZUGANGSKONTROLLE',
      'ZUGRIFFSKONTROLLE',
      'WEITERGABEKONTROLLE',
      'EINGABEKONTROLLE',
      'AUFTRAGSKONTROLLE',
      'VERFUEGBARKEITSKONTROLLE',
      'TRENNUNGSGEBOT',
    ]

    return categories.reduce(
      (acc, cat) => {
        acc[cat] = state.toms.filter(t => t.category === cat)
        return acc
      },
      {} as Record<TOMCategory, TOM[]>
    )
  })

  const addTOM = (tom: Omit<TOM, 'id' | 'createdAt' | 'updatedAt'>): void => {
    dispatch({ type: 'ADD_TOM', payload: tom })
  }

  const updateTOM = (id: string, updates: Partial<TOM>): void => {
    dispatch({ type: 'UPDATE_TOM', payload: { id, updates } })
  }

  const deleteTOM = (id: string): void => {
    dispatch({ type: 'DELETE_TOM', payload: id })
  }

  // DSFA
  const dsfas = computed(() => state.dsfas)

  const createDSFA = (title: string, description: string): DSFA => {
    return dsgvo.createDSFA(title, description)
  }

  const updateDSFA = (id: string, updates: Partial<DSFA>): void => {
    dispatch({ type: 'UPDATE_DSFA', payload: { id, updates } })
  }

  // Retention
  const retentionPolicies = computed(() => state.retentionPolicies)

  const addRetentionPolicy = (policy: Omit<RetentionPolicy, 'id'>): void => {
    dispatch({ type: 'ADD_RETENTION_POLICY', payload: policy })
  }

  const updateRetentionPolicy = (id: string, updates: Partial<RetentionPolicy>): void => {
    dispatch({ type: 'UPDATE_RETENTION_POLICY', payload: { id, updates } })
  }

  const deleteRetentionPolicy = (id: string): void => {
    dispatch({ type: 'DELETE_RETENTION_POLICY', payload: id })
  }

  return {
    dsrRequests,
    pendingDSRCount,
    submitDSR,
    updateDSRStatus,
    consents,
    activeConsents,
    hasConsent,
    recordConsent,
    revokeConsent,
    processingActivities,
    addProcessingActivity,
    updateProcessingActivity,
    deleteProcessingActivity,
    toms,
    tomsByCategory,
    addTOM,
    updateTOM,
    deleteTOM,
    dsfas,
    createDSFA,
    updateDSFA,
    retentionPolicies,
    addRetentionPolicy,
    updateRetentionPolicy,
    deleteRetentionPolicy,
    isLoading,
  }
}
