import { Injectable } from '@angular/core';
import axios from 'axios';

import { BASE_URL } from '../config/api.config';

export enum ConsentType {
  PRIVACY_POLICY = 'PRIVACY_POLICY',
  COOKIES = 'COOKIES',
  MARKETING = 'MARKETING',
  DATA_PROCESSING = 'DATA_PROCESSING',
  THIRD_PARTY_SHARING = 'THIRD_PARTY_SHARING',
  ANALYTICS = 'ANALYTICS',
  ADVERTISING = 'ADVERTISING'
}

export enum ConsentStatus {
  GRANTED = 'GRANTED',
  DENIED = 'DENIED',
  WITHDRAWN = 'WITHDRAWN',
  PENDING = 'PENDING'
}

export enum DataSubjectRequestType {
  ACCESS = 'ACCESS',
  RECTIFICATION = 'RECTIFICATION',
  ERASURE = 'ERASURE',
  RESTRICTION = 'RESTRICTION',
  PORTABILITY = 'PORTABILITY',
  OBJECTION = 'OBJECTION'
}

export interface DataSubjectConsent {
  id: string;
  userId: string;
  consentType: ConsentType;
  consentStatus: ConsentStatus;
  consentVersion?: string;
  consentMethod?: string;
  grantedAt?: string;
  withdrawnAt?: string;
  expiresAt?: string;
  createdAt: string;
  updatedAt: string;
}

export interface DataSubjectRequest {
  id: string;
  userId: string;
  requestType: DataSubjectRequestType;
  requestStatus: string;
  description?: string;
  requestedAt: string;
  completedAt?: string;
  rejectedAt?: string;
  rejectionReason?: string;
  responseData?: any;
  verificationToken?: string;
  verifiedAt?: string;
}

@Injectable({
  providedIn: 'root'
})
export class GdprService {
  private getAuthHeaders() {
    const token = localStorage.getItem('jwtToken');
    return token ? { Authorization: `Bearer ${token}` } : {};
  }

  async grantConsent(consentType: ConsentType, consentVersion?: string, consentMethod: string = 'WEB_FORM'): Promise<DataSubjectConsent> {
    const response = await axios.post(
      `${BASE_URL}/api/v3/gdpr/consent`,
      null,
      {
        params: { consentType, consentVersion, consentMethod },
        headers: this.getAuthHeaders()
      }
    );
    return response.data;
  }

  async withdrawConsent(consentType: ConsentType): Promise<DataSubjectConsent> {
    const response = await axios.post(
      `${BASE_URL}/api/v3/gdpr/consent/withdraw`,
      null,
      {
        params: { consentType },
        headers: this.getAuthHeaders()
      }
    );
    return response.data;
  }

  async getUserConsents(): Promise<DataSubjectConsent[]> {
    const response = await axios.get(
      `${BASE_URL}/api/v3/gdpr/consent`,
      { headers: this.getAuthHeaders() }
    );
    return response.data;
  }

  async checkConsent(consentType: ConsentType): Promise<boolean> {
    try {
      const response = await axios.get(
        `${BASE_URL}/api/v3/gdpr/consent/check`,
        {
          params: { consentType },
          headers: this.getAuthHeaders()
        }
      );
      return response.data.hasConsent || false;
    } catch (error) {
      return false;
    }
  }

  async requestAccess(description?: string): Promise<DataSubjectRequest> {
    const response = await axios.post(
      `${BASE_URL}/api/v3/gdpr/request/access`,
      null,
      {
        params: { description },
        headers: this.getAuthHeaders()
      }
    );
    return response.data;
  }

  async requestErasure(description?: string): Promise<DataSubjectRequest> {
    const response = await axios.post(
      `${BASE_URL}/api/v3/gdpr/request/erasure`,
      null,
      {
        params: { description },
        headers: this.getAuthHeaders()
      }
    );
    return response.data;
  }

  async requestRectification(description?: string): Promise<DataSubjectRequest> {
    const response = await axios.post(
      `${BASE_URL}/api/v3/gdpr/request/rectification`,
      null,
      {
        params: { description },
        headers: this.getAuthHeaders()
      }
    );
    return response.data;
  }

  async requestPortability(description?: string): Promise<DataSubjectRequest> {
    const response = await axios.post(
      `${BASE_URL}/api/v3/gdpr/request/portability`,
      null,
      {
        params: { description },
        headers: this.getAuthHeaders()
      }
    );
    return response.data;
  }

  async getUserRequests(): Promise<DataSubjectRequest[]> {
    const response = await axios.get(
      `${BASE_URL}/api/v3/gdpr/request`,
      { headers: this.getAuthHeaders() }
    );
    return response.data;
  }

  async verifyRequest(token: string): Promise<DataSubjectRequest> {
    const response = await axios.post(
      `${BASE_URL}/api/v3/gdpr/request/verify`,
      null,
      {
        params: { token },
        headers: this.getAuthHeaders()
      }
    );
    return response.data;
  }

  // Check if consent banner should be shown
  shouldShowConsentBanner(): boolean {
    const consentBannerShown = localStorage.getItem('gdpr_consent_banner_shown');
    return !consentBannerShown;
  }

  // Mark consent banner as shown
  markConsentBannerShown(): void {
    localStorage.setItem('gdpr_consent_banner_shown', 'true');
  }

  // Check if user has granted all required consents
  async hasRequiredConsents(): Promise<boolean> {
    try {
      const privacyPolicy = await this.checkConsent(ConsentType.PRIVACY_POLICY);
      const dataProcessing = await this.checkConsent(ConsentType.DATA_PROCESSING);
      return privacyPolicy && dataProcessing;
    } catch (error) {
      return false;
    }
  }
}

