import { nanoid } from "nanoid";

import type {
  AdapterFetchInput,
  PerformanceAdapter,
  PerformanceSnapshot,
} from "./types";
import { manualPerformanceInputSchema, performanceSnapshotSchema } from "./validation";

interface ManualAdapterFetchInput extends AdapterFetchInput {
  manualInput: unknown;
}

interface ManualPerformanceAdapter extends Omit<PerformanceAdapter, "fetch"> {
  fetch(input: ManualAdapterFetchInput): Promise<PerformanceSnapshot>;
}

export function createManualPerformanceAdapter(): ManualPerformanceAdapter {
  return {
    source: "manual",
    async fetch(input) {
      const parsed = manualPerformanceInputSchema.parse(input.manualInput);
      return performanceSnapshotSchema.parse({
        id: `perf_${nanoid(10)}`,
        publication_id: input.publication.id,
        source: "manual",
        window_label: parsed.window_label,
        metrics: parsed.metrics,
        feedback_summary: parsed.feedback_summary,
        raw_reference: parsed.raw_reference,
        snapshot_at: new Date().toISOString(),
      });
    },
  };
}
