// ── Validate configured manifest URL ──
// Fetches the URL and confirms it returns a valid Stremio manifest.

import { ValidationResult } from "./models";

export async function validateConfiguredManifest(
  configuredManifestUrl: string,
): Promise<ValidationResult> {
  try {
    const response = await fetch(configuredManifestUrl, {
      headers: {
        "User-Agent": "Unspooled-AddonConfig/1.0",
        Accept: "application/json",
      },
    });

    if (!response.ok) {
      return {
        valid: false,
        error: `HTTP ${response.status}: ${response.statusText}`,
        manifestName: null,
      };
    }

    const body = (await response.json()) as Record<string, unknown>;

    // Must have id and name to be a valid Stremio manifest
    if (!body.id) {
      return {
        valid: false,
        error: "Invalid manifest: missing 'id' field",
        manifestName: null,
      };
    }
    if (!body.name) {
      return {
        valid: false,
        error: "Invalid manifest: missing 'name' field",
        manifestName: null,
      };
    }

    // Must expose at least one resource
    const resources = body.resources as Array<unknown> | undefined;
    if (!resources || resources.length === 0) {
      return {
        valid: false,
        error: "Invalid manifest: missing 'resources' array",
        manifestName: null,
      };
    }

    return {
      valid: true,
      error: null,
      manifestName: body.name as string,
    };
  } catch (e) {
    return {
      valid: false,
      error: (e as Error).message,
      manifestName: null,
    };
  }
}
