import { Injectable } from '@angular/core';
import { Apollo, gql } from 'apollo-angular';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class DataPrivacyService {
  constructor(private apollo: Apollo) {}

  downloadDataExportJson(userId: number): void {
    this.exportDataPrivacy(userId).subscribe(dataString => {
      const jsonData = JSON.stringify(JSON.parse(dataString), null, 2); // Format nicely
      const blob = new Blob([jsonData], { type: 'application/json' });
      const url = window.URL.createObjectURL(blob);

      const anchor = document.createElement('a');
      anchor.href = url;
      anchor.download = 'exported-data.json';
      anchor.click();

      window.URL.revokeObjectURL(url);
    });
  }

  exportDataPrivacy(userId: number): Observable<string> {
    return this.apollo
      .mutate<{ privacy: { exportData: string } }>({
        mutation: gql`
          mutation exportDataPrivacy($userId: Int!) {
            privacy {
              exportData(userId: $userId)
            }
          }
        `,
        variables: {
          userId,
        },
      })
      .pipe(map(result => result.data?.privacy.exportData ?? ''));
  }

  anonymizeData(userId: number): Observable<boolean> {
    return this.apollo
      .mutate<{ privacy: { anonymizeData: boolean } }>({
        mutation: gql`
          mutation anonymizeDataPrivacy($userId: Int!) {
            privacy {
              anonymizeData(userId: $userId)
            }
          }
        `,
        variables: {
          userId,
        },
      })
      .pipe(map(result => result.data?.privacy.anonymizeData ?? false));
  }

  deleteData(userId: number): Observable<boolean> {
    return this.apollo
      .mutate<{ privacy: { deleteData: boolean } }>({
        mutation: gql`
          mutation deleteDataPrivacy($userId: Int!) {
            privacy {
              deleteData(userId: $userId)
            }
          }
        `,
        variables: {
          userId,
        },
      })
      .pipe(map(result => result.data?.privacy.deleteData ?? false));
  }
}
