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 { IPagesRepository } from "../../application/repositories/pages.repository.interface";
import type { Page } from "../../entities/models/page";

type PayloadPageDoc = {
  id: string | number;
  title?: string | null;
  slug?: string | null;
  hero?:
    | {
        heading?: string | null;
        subheading?: string | null;
        image?: string | number | { id: string | number } | null;
      }
    | null;
  layout?: unknown[] | null;
  status?: string | null;
  publishedAt?: string | null;
  seo?: { title?: string | null; description?: string | null } | null;
  createdAt?: string | null;
  updatedAt?: string | null;
};

function mapDoc(doc: PayloadPageDoc): Page {
  const imageId =
    doc.hero && typeof doc.hero.image === "object" && doc.hero.image !== null
      ? String(doc.hero.image.id)
      : doc.hero?.image != null
        ? String(doc.hero.image)
        : undefined;

  return {
    id: String(doc.id),
    title: doc.title ?? "",
    slug: doc.slug ?? "",
    hero: {
      heading: doc.hero?.heading ?? "",
      subheading: doc.hero?.subheading ?? undefined,
      imageId,
    },
    layout: doc.layout ?? [],
    status: doc.status === "published" ? "published" : "draft",
    publishedAt: doc.publishedAt ? new Date(doc.publishedAt) : null,
    seo: {
      title: doc.seo?.title ?? "",
      description: doc.seo?.description ?? undefined,
    },
    createdAt: doc.createdAt ? new Date(doc.createdAt) : new Date(0),
    updatedAt: doc.updatedAt ? new Date(doc.updatedAt) : new Date(0),
  };
}

const FEATURE = "marketing-pages" as const;
const REPO = "pages" as const;

@injectable()
export class PagesRepository implements IPagesRepository {
  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 getPageBySlug(slug: string): Promise<Page | undefined> {
    return this.tracer.startSpan(
      { name: "pages.getPageBySlug", op: "repository", attributes: { slug } },
      async (span) => {
        try {
          const payload = await getPayload({ config: this.config });
          const result = await payload.find({
            collection: "pages",
            where: { slug: { equals: slug } },
            limit: 1,
            overrideAccess: true,
          });
          const doc = result.docs[0] as PayloadPageDoc | undefined;
          span.setAttribute("found", Boolean(doc));
          return doc ? mapDoc(doc) : undefined;
        } catch (err) {
          this.logger.captureException(err, {
            tags: { feature: FEATURE, repo: REPO, method: "getPageBySlug" },
          });
          span.setStatus("error", err instanceof Error ? err.message : String(err));
          throw err;
        }
      },
    );
  }

  async getPages(options?: {
    status?: string;
    limit?: number;
    offset?: number;
  }): Promise<Page[]> {
    return this.tracer.startSpan(
      {
        name: "pages.getPages",
        op: "repository",
        attributes: {
          status: options?.status ?? null,
          limit: options?.limit ?? null,
          offset: options?.offset ?? null,
        },
      },
      async (span) => {
        try {
          const payload = await getPayload({ config: this.config });
          const where: Record<string, { equals: string }> = {};
          if (options?.status) where.status = { equals: options.status };
          const result = await payload.find({
            collection: "pages",
            where: where as never,
            limit: options?.limit ?? 50,
            page: options?.offset
              ? Math.floor(options.offset / (options.limit ?? 50)) + 1
              : 1,
            overrideAccess: true,
          });
          const pages = result.docs.map((d) => mapDoc(d as PayloadPageDoc));
          span.setAttribute("count", pages.length);
          return pages;
        } catch (err) {
          this.logger.captureException(err, {
            tags: { feature: FEATURE, repo: REPO, method: "getPages" },
          });
          span.setStatus("error", err instanceof Error ? err.message : String(err));
          throw err;
        }
      },
    );
  }
}
