import { useMutation } from '@tanstack/react-query';
import { gql } from 'graphql-request';
import { fetchGraphQL } from '../client';

// GraphQL Mutations
const EXPORT_SAFT_MUTATION = gql`
  mutation ExportSaftFile($companyId: ID!, $fiscalYearId: ID!) {
    exportSaftFile(companyId: $companyId, fiscalYearId: $fiscalYearId) {
      success
      xmlContent
      fileName
      errorCode
      errorMessage
    }
  }
`;

// Response types
export interface SaftExportResult {
  success: boolean;
  xmlContent?: string;
  fileName?: string;
  errorCode?: string;
  errorMessage?: string;
}

interface ExportSaftResponse {
  exportSaftFile: SaftExportResult;
}

// Input types
export interface ExportSaftInput {
  companyId: string;
  fiscalYearId: string;
}

/**
 * Hook to export SAF-T file for a company and fiscal year.
 * Returns XML content that can be downloaded as a file.
 */
export function useExportSaft() {
  return useMutation({
    mutationFn: async (input: ExportSaftInput) => {
      // Pass variables directly (companyId, fiscalYearId) - not wrapped in input object
      const data = await fetchGraphQL<ExportSaftResponse>(EXPORT_SAFT_MUTATION, {
        companyId: input.companyId,
        fiscalYearId: input.fiscalYearId,
      });
      return data.exportSaftFile;
    },
  });
}

/**
 * Helper function to download SAF-T XML content as a file.
 */
export function downloadSaftFile(result: SaftExportResult): void {
  if (!result.xmlContent || !result.fileName) {
    throw new Error('No SAF-T content to download');
  }

  const blob = new Blob([result.xmlContent], { type: 'application/xml;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = result.fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}
