// VAT (Moms) queries for SKAT compliance reporting

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

// Response types matching backend VatReportDto
export interface VatReportResponse {
  // SKAT boxes (VAT amounts)
  boxA: number; // Salgsmoms (Output VAT)
  boxB: number; // Købsmoms (Input VAT deduction)
  boxC: number; // EU-varekøb moms
  boxD: number; // Ydelseskøb moms

  // Basis/turnover fields
  basis1: number; // Salg med moms
  basis2: number; // Salg uden moms (export)
  basis3: number; // EU-varekøb
  basis4: number; // Ydelseskøb fra udland

  // Summary
  totalOutputVat: number;
  totalInputVat: number;
  netVat: number;

  // Period info
  periodStart: string;
  periodEnd: string;
  transactionCount: number;
}

const VAT_REPORT_QUERY = gql`
  query VatReport($companyId: ID!, $periodStart: DateOnly!, $periodEnd: DateOnly!) {
    vatReport(companyId: $companyId, periodStart: $periodStart, periodEnd: $periodEnd) {
      boxA
      boxB
      boxC
      boxD
      basis1
      basis2
      basis3
      basis4
      totalOutputVat
      totalInputVat
      netVat
      periodStart
      periodEnd
      transactionCount
    }
  }
`;

interface VatReportQueryResponse {
  vatReport: VatReportResponse;
}

/**
 * Hook to fetch a VAT report for a company within a date range.
 *
 * @param companyId - The company ID
 * @param periodStart - Start date in YYYY-MM-DD format
 * @param periodEnd - End date in YYYY-MM-DD format
 */
export function useVatReport(
  companyId: string | undefined,
  periodStart: string | undefined,
  periodEnd: string | undefined
) {
  return useQuery({
    queryKey: createQueryKey('vatReport', { companyId, periodStart, periodEnd }),
    queryFn: async () => {
      const data = await fetchGraphQL<VatReportQueryResponse>(VAT_REPORT_QUERY, {
        companyId,
        periodStart,
        periodEnd,
      });
      return data.vatReport;
    },
    enabled: !!companyId && !!periodStart && !!periodEnd,
  });
}
