import { readFile } from "node:fs/promises";
import path from "node:path";

import { describe, expect, it } from "vitest";
import Parser from "rss-parser";

import { normalizePodcastFeedItems } from "../src/lib/ingest/podcast";
import { normalizeYoutubeApiVideos, normalizeYoutubeRssFeedItems } from "../src/lib/ingest/youtube";

const fixturesDir = path.join(process.cwd(), "tests", "fixtures");

describe("ingestion normalization", () => {
  it("normalizes YouTube RSS/Atom feed items", async () => {
    const xml = await readFile(path.join(fixturesDir, "youtube-feed.xml"), "utf8");
    const parser = new Parser();
    const feed = await parser.parseString(xml);
    const items = normalizeYoutubeRssFeedItems(feed.items || [], 10);

    expect(items.length).toBeGreaterThan(0);
    expect(items[0].source).toBe("youtube");
    expect(items[0].title).toBeTruthy();
    expect(items[0].url).toMatch(/youtube\.com/);
    expect(items[0].publishedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
  });

  it("normalizes YouTube API videos and captures view count", async () => {
    const raw = await readFile(path.join(fixturesDir, "youtube-videos.json"), "utf8");
    const json = JSON.parse(raw) as any;
    const items = normalizeYoutubeApiVideos(json.items);

    expect(items).toHaveLength(1);
    expect(items[0].metrics?.views).toBe(12345);
  });

  it("normalizes podcast RSS items and ensures ISO dates", async () => {
    const xml = await readFile(path.join(fixturesDir, "podcast-feed.xml"), "utf8");
    const parser = new Parser();
    const feed = await parser.parseString(xml);
    const items = normalizePodcastFeedItems(feed.items || [], 10);

    expect(items).toHaveLength(1);
    expect(items[0].source).toBe("podcast");
    expect(items[0].publishedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
  });
});
