// TODO: remove or update later. temp sample of new fuseki queries
import { cache } from 'react';

import 'server-only';

const artisticClassificationsQuery = `
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX azopus: <https://azopus.hu/ontology/>

SELECT
  ?schemeId
  ?id
  ?labelHu
  ?labelEn
WHERE {
  VALUES ?scheme {
    azopus:CS0000005
    azopus:CS0000006
  }

  ?concept
    skos:inScheme ?scheme ;
    skos:notation ?id .

  BIND(REPLACE(STR(?scheme), "^.*/", "") AS ?schemeId)

  OPTIONAL {
    ?concept skos:prefLabel ?labelHu .
    FILTER(LANG(?labelHu) = "hu")
  }
  OPTIONAL {
    ?concept skos:prefLabel ?labelEn .
    FILTER(LANG(?labelEn) = "en")
  }
}
ORDER BY ?schemeId ?id
`;

type SparqlValue = {
  value: string;
};

type SparqlRow = Record<string, SparqlValue | undefined>;

type SparqlSelectResponse = {
  results?: {
    bindings?: SparqlRow[];
  };
};

type LocalizedText = {
  hu: string | null;
  en: string | null;
};

export type ArtisticClassification = {
  schemeId: string;
  id: string;
  label: LocalizedText;
};

const bindingValue = (row: SparqlRow, key: string): string | null => row[key]?.value ?? null;

const requiredBindingValue = (row: SparqlRow, key: string): string => {
  const value = bindingValue(row, key);
  if (!value) throw new Error(`Missing Fuseki binding: ${key}`);
  return value;
};

export const getArtisticClassifications = cache(async (): Promise<ArtisticClassification[]> => {
  const username = process.env.FUSEKI_USERNAME;
  const password = process.env.FUSEKI_PASSWORD;
  const endpoint = process.env.FUSEKI_QUERY_URL;

  if (!username || !password || !endpoint) {
    throw new Error('Missing Fuseki configuration.');
  }

  const authorization = Buffer.from(`${username}:${password}`).toString('base64');
  const response = await fetch(endpoint, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${authorization}`,
      Accept: 'application/sparql-results+json',
      'Content-Type': 'application/sparql-query',
    },
    body: artisticClassificationsQuery,
  });

  if (!response.ok) {
    throw new Error(`Fuseki query failed with status ${response.status}.`);
  }

  const payload = (await response.json()) as SparqlSelectResponse;
  const classifications = (payload.results?.bindings ?? []).map((row) => ({
    schemeId: requiredBindingValue(row, 'schemeId'),
    id: requiredBindingValue(row, 'id'),
    label: {
      hu: bindingValue(row, 'labelHu'),
      en: bindingValue(row, 'labelEn'),
    },
  }));

  return classifications;
});
