---
import { Code } from 'astro-expressive-code/components';
import fs from 'fs';

import VerticalSideBarLayout from '@layouts/VerticalSideBarLayout.astro';
import Footer from '@layouts/Footer.astro';
import { Page } from './_[filename].data';
import { getAbsoluteFilePathForAstroFile } from '@utils/files';
import { buildUrl, buildEditUrlForResource } from '@utils/url-builder';
import Admonition from '@components/MDX/Admonition';
import Badge from '@components/Badge.astro';

import { ServerIcon } from '@heroicons/react/24/outline';

export const prerender = Page.prerender;
export const getStaticPaths = Page.getStaticPaths;

// Get data
const { collection, data, filePath, filename, path: relativeSpecPath } = await Page.getData(Astro);

const fileName = filename || 'schema.graphql';
const pathToSpec = getAbsoluteFilePathForAstroFile(filePath, fileName);
const fileExists = fs.existsSync(pathToSpec);
const isRemote = relativeSpecPath.includes('https://');
let content = '';

if (fileExists && !isRemote) {
  content = fs.readFileSync(pathToSpec, 'utf8');
}

if (isRemote) {
  // Fetch the content from the remote path
  content = await fetch(relativeSpecPath).then((res) => res.text());
}

// Create comprehensive page title
const pageTitle = `${collection} | ${data.name} | GraphQL Schema`.replace(/^\w/, (c) => c.toUpperCase());

const getServiceBadge = () => {
  return [{ textColor: 'gray', content: 'Service', icon: ServerIcon }];
};

const getGraphQLBadge = () => {
  return [
    {
      textColor: 'gray',
      content: 'GraphQL Schema',
      iconURL: buildUrl('/icons/graphql.svg', true),
      id: 'graphql-schema-badge',
    },
  ];
};

const badges = [...getServiceBadge(), ...getGraphQLBadge()];

// Index only the latest version
const pagefindAttributes =
  data.version === data.latestVersion
    ? {
        'data-pagefind-body': '',
        'data-pagefind-meta': `title:${pageTitle}`,
      }
    : {};
---

<VerticalSideBarLayout title={pageTitle} description={`GraphQL schema for ${data.name}`}>
  <main class="flex docs-layout min-h-full bg-[rgb(var(--ec-page-bg))]" {...pagefindAttributes}>
    <div class="flex docs-layout w-full">
      <div class="w-full lg:mr-2 pr-24 py-8 bg-[rgb(var(--ec-page-bg))]">
        <div class="border-b border-[rgb(var(--ec-page-border))] md:pb-2">
          <div>
            <div class="flex justify-between items-start">
              <div class="flex-1">
                <h1 class="text-2xl md:text-4xl font-bold text-[rgb(var(--ec-page-text))] mb-2">
                  {data.name}
                  <span class="text-[rgb(var(--ec-page-text-muted))]">(v{data.version})</span>
                </h1>
                <h2 class="text-lg text-[rgb(var(--ec-page-text-muted))] font-medium mb-1">GraphQL Schema</h2>
              </div>
            </div>

            {
              badges && badges.length > 0 && (
                <div class="flex flex-wrap gap-3 py-4">
                  {badges.map((badge: any) => {
                    return <Badge badge={badge} />;
                  })}
                </div>
              )
            }
          </div>
        </div>

        <div data-pagefind-ignore>
          {
            data.version !== data.latestVersion && (
              <Admonition type="warning" title="New version found">
                <p>
                  You are looking at a previous version of the service <strong>{data.name}</strong>.{' '}
                  <a
                    class="underline block pt-2"
                    href={buildUrl(`/docs/${collection}/${data.id}/${data.latestVersion}/graphql/${filename}`)}
                  >
                    The latest version of this GraphQL schema is
                    <span>v{data.latestVersion}</span> &rarr;
                  </a>
                </p>
              </Admonition>
            )
          }
        </div>

        {
          !fileExists && (
            <Admonition type="warning" title="Schema not found">
              <p>The GraphQL schema file could not be found at the expected location.</p>
            </Admonition>
          )
        }

        {
          fileExists && content && (
            <div class="mt-6">
              <div class="bg-[rgb(var(--ec-card-bg))] rounded-lg p-4 mb-4 border border-[rgb(var(--ec-page-border))]">
                <div class="flex items-center gap-2 mb-2">
                  <img src={buildUrl('/icons/graphql.svg', true)} class="w-5 h-5" alt="GraphQL" />
                  <h3 class="text-lg font-semibold text-[rgb(var(--ec-page-text))]">GraphQL Schema</h3>
                </div>
                <p class="text-sm text-[rgb(var(--ec-page-text-muted))]">
                  This schema defines the GraphQL API structure including types, queries, mutations, and subscriptions for{' '}
                  {data.name}.
                </p>
              </div>

              <div class="not-prose overflow-x-auto">
                <Code code={content} title={`${data.name} v${data.version} - Schema`} lang="graphql" />
              </div>
            </div>
          )
        }

        <Footer />
      </div>
    </div>
  </main>

  <style is:global>
    .docs-layout .prose {
      max-width: none;
      overflow: auto;
    }
  </style>
</VerticalSideBarLayout>
