import { Handlers } from "$fresh/server.ts";
import { createStreamResponse } from "@lib/helpers.ts";
import { getAllMovies, Movie } from "@lib/resource/movies.ts";
import * as tmdb from "@lib/tmdb.ts";
import {
  createRecommendationResource,
  getRecommendation,
} from "@lib/recommendation.ts";
import { AccessDeniedError } from "@lib/errors.ts";

async function processUpdateRecommendations(
  streamResponse: ReturnType<typeof createStreamResponse>,
) {
  const allMovies = await getAllMovies();

  const movies = allMovies.filter((m) => {
    if (!m?.meta) return false;
    if (!m.meta.rating) return false;
    if (!m.meta.tmdbId) return false;
    return true;
  }) as Movie[];

  streamResponse.enqueue("Fetched all movies");

  let done = 0;
  const total = movies.length;

  await Promise.all(movies.map(async (movie) => {
    if (!movie.meta.tmdbId) return;
    if (!movie.meta.rating) return;
    const recommendation = getRecommendation(movie.id, movie.type);
    if (recommendation) {
      done++;
      return;
    }
    try {
      const movieDetails = await tmdb.getMovie(movie.meta.tmdbId);
      await createRecommendationResource(movie, movieDetails.overview);
    } catch (err) {
      console.log(err);
    }
    done++;
    streamResponse.enqueue(
      `${Math.floor((done / total) * 100)}% [${done + 1}/${total}] ${movie.id}`,
    );
  })).catch((err) => {
    console.log(err);
  });

  streamResponse.enqueue("100% Finished");
}

export const handler: Handlers = {
  GET(_, ctx) {
    const session = ctx.state.session;
    if (!session) {
      throw new AccessDeniedError();
    }

    const streamResponse = createStreamResponse();
    processUpdateRecommendations(streamResponse);

    return streamResponse.response;
  },
};
