import { type NextRequest, NextResponse } from 'next/server';

import { getCreationList, getCreatorRecommendations } from '@/services/creations';

import { shuffle } from '@/utils/array';
import { getCreationCreators } from '@/utils/creationHelpers';

import type { CreationListItem } from '@/types/Creation';

/* ============================================================================
   CREATION RECOMMENDATIONS  —  feeds the tabbed recommender on the work page.
   ----------------------------------------------------------------------------
   Two tab kinds share this route:
     • type=recommended → personControl/getDataWithRecommendation (creator-based
       "others viewed this" pool, the `ajanlas` array).
     • type=tag         → contentControl/getList scoped to a single subject tag.
   Both pools get the same treatment: drop the creation being viewed, then
   randomize and cut to MAX_ITEMS. Re-fetching a tab therefore surfaces a fresh
   random slice each time. The payload is stripped to just the fields the
   carousel card renders (mapCreationToCarouselItem).
   ========================================================================== */

// hard cap on how many cards a tab shows; also the size of the random slice.
const MAX_ITEMS = 16;

// strip to only the fields the carousel card needs (see mapCreationToCarouselItem)
function toRecommendationCard(item: CreationListItem) {
  return {
    id: item.id,
    alkotasAzonosito: item.alkotasAzonosito,
    nev: item.nev ?? null,
    label: item.label ?? null,
    alkoto: getCreationCreators(item),
    fokep: item.fokep ?? null,
    fokepId: item.fokepId ?? null,
    fokepNev: item.fokepNev ?? null,
    kepek: Array.isArray(item.kepek) ? item.kepek : [],
    hivatkozas: item.hivatkozas ?? null,
    cardType: item.cardType ?? 'creation',
    tipus: item.tipus ?? null,
  };
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const type = searchParams.get('type');
    // the creator whose page we're on — required by the recommended pool.
    const identifier = searchParams.get('identifier')?.trim() || null;
    // the creation being viewed — dropped so we never recommend the work the
    // user is already looking at.
    const excludeId = searchParams.get('excludeId')?.trim() || null;

    let list: CreationListItem[] = [];

    if (type === 'tag') {
      const tagId = Number(searchParams.get('tagId'));
      if (!Number.isFinite(tagId)) {
        return NextResponse.json(
          { success: false, error: 'Missing or invalid tagId' },
          { status: 400 }
        );
      }

      list = await getCreationList({
        maxResults: 5000,
        conceptionIdList: [tagId],
        imageNeeded: true,
      });
    } else if (type === 'recommended') {
      if (!identifier) {
        return NextResponse.json({ success: false, error: 'Missing identifier' }, { status: 400 });
      }

      list = await getCreatorRecommendations(identifier);
    } else {
      return NextResponse.json({ success: false, error: 'Invalid type' }, { status: 400 });
    }

    // same treatment for both pools: drop the viewed creation, randomize, cap.
    const pool = excludeId ? list.filter((item) => item.alkotasAzonosito !== excludeId) : list;
    const data = shuffle(pool).slice(0, MAX_ITEMS).map(toRecommendationCard);

    return NextResponse.json({ success: true, data });
  } catch (error) {
    console.error('Error fetching creation recommendations:', error);
    return NextResponse.json(
      {
        success: false,
        error: 'Failed to fetch recommendations',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}
