import "reflect-metadata";
import { injectable } from "inversify";
import { getPayload } from "payload";
import type { SanitizedConfig } from "payload";
import {
  NoopTracer,
  NoopLogger,
  type ITracer,
  type ILogger,
} from "@repo/core-shared/instrumentation";

import type { IHeaderRepository } from "../../application/repositories/header.repository.interface";
import type { Header, HeaderItem } from "../../entities/models/header";

type PayloadHeaderGlobal = {
  logo?: string | number | { id: string | number } | null;
  items?: Array<{
    label?: string | null;
    href?: string | null;
    external?: boolean | null;
  }> | null;
};

const FEATURE = "navigation" as const;
const REPO = "header" as const;

@injectable()
export class HeaderRepository implements IHeaderRepository {
  private config: SanitizedConfig;
  private tracer: ITracer;
  private logger: ILogger;

  constructor(
    config: SanitizedConfig,
    tracer: ITracer = new NoopTracer(),
    logger: ILogger = new NoopLogger(),
  ) {
    this.config = config;
    this.tracer = tracer;
    this.logger = logger;
  }

  async getHeader(): Promise<Header> {
    return this.tracer.startSpan(
      { name: "header.getHeader", op: "repository", attributes: {} },
      async (span) => {
        try {
          const payload = await getPayload({ config: this.config });
          const doc = (await payload.findGlobal({
            slug: "header",
            overrideAccess: true,
          })) as PayloadHeaderGlobal;

          const logoId =
            typeof doc.logo === "object" && doc.logo !== null
              ? String(doc.logo.id)
              : doc.logo != null
                ? String(doc.logo)
                : undefined;

          const items: HeaderItem[] = (doc.items ?? []).map((item) => ({
            label: item.label ?? "",
            href: item.href ?? "",
            external: item.external ?? false,
          }));

          span.setAttribute("itemCount", items.length);
          return { logoId, items };
        } catch (err) {
          this.logger.captureException(err, {
            tags: { feature: FEATURE, repo: REPO, method: "getHeader" },
          });
          span.setStatus("error", err instanceof Error ? err.message : String(err));
          throw err;
        }
      },
    );
  }
}
