import { useMutation, useQueryClient } from '@tanstack/react-query';
import { gql } from 'graphql-request';
import { fetchGraphQL, createQueryKey } from '../client';
import type { AccountType } from '@/types/accounting';

// GraphQL Mutations
const CREATE_ACCOUNT_MUTATION = gql`
  mutation CreateAccount($input: CreateAccountInput!) {
    createAccount(input: $input) {
      id
      companyId
      accountNumber
      name
      accountType
      parentId
      description
      vatCodeId
      isActive
      isSystemAccount
      standardAccountNumber
      createdAt
      updatedAt
    }
  }
`;

// Input types
export interface CreateAccountInput {
  companyId: string;
  accountNumber: string;
  name: string;
  accountType: AccountType;
  parentId?: string;
  description?: string;
  vatCodeId?: string;
  isSystemAccount?: boolean;
  /** Erhvervsstyrelsens standardkontonummer for SAF-T rapportering */
  standardAccountNumber?: string;
}

// Response types
interface AccountResponse {
  id: string;
  companyId: string;
  accountNumber: string;
  name: string;
  accountType: string;
  parentId?: string;
  description?: string;
  vatCodeId?: string;
  isActive: boolean;
  isSystemAccount: boolean;
  createdAt: string;
  updatedAt: string;
}

interface CreateAccountResponse {
  createAccount: AccountResponse;
}

/**
 * Hook to create a new account
 */
export function useCreateAccount() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (input: CreateAccountInput) => {
      // Convert accountType to GraphQL enum format (uppercase)
      const graphqlInput = {
        ...input,
        accountType: input.accountType.toUpperCase(),
      };
      const data = await fetchGraphQL<CreateAccountResponse>(CREATE_ACCOUNT_MUTATION, { input: graphqlInput });
      return data.createAccount;
    },
    onSuccess: (_, variables) => {
      // Invalidate accounts for the company
      queryClient.invalidateQueries({ queryKey: createQueryKey('accounts', { companyId: variables.companyId }) });
      queryClient.invalidateQueries({ queryKey: createQueryKey('activeAccounts', { companyId: variables.companyId }) });
    },
  });
}
