<?php
namespace App\Repositories\Website;

use App\Repositories\Interfaces\Website\FavoriteRepositoryInterface;


class FavoriteRepository implements FavoriteRepositoryInterface
{
    public function getfavorites()
    {
        $user = auth()->user();

        return [
            'movies' => $user->favoriteMovies()->get()->map(function ($movie) {
                return [
                    'id' => $movie->id,
                    'title' => $movie->title,
                    'thumbnail' => apiImage(optional(json_decode($movie->thumbnail))->original_image, 'movies'),
                    'is_free' => $movie->is_free,
                    'is_rental' => $movie->is_rental,
                    'rental_price' => $movie->rental_price,
                    'rental_duration' => $movie->rental_duration,
                ];
            }),
            'tv_shows' => $user->favoriteTvShows()?->get()->map(function ($show) {
                return [
                    'id' => $show->id,
                    'title' => $show->title,
                    'thumbnail' => apiImage(optional(json_decode($show->thumbnail))->original_image, 'tv_shows'),
                    'is_free' => $show->is_free,
                    'is_rental' => $show->is_rental,
                    'rental_price' => $show->rental_price,
                    'rental_duration' => $show->rental_duration,
                ];
            }) ?? [],
            'live_tvs' => $user->favoriteLiveTvs()?->get()->map(function ($live_tv) {
                return [
                    'id' => $live_tv->id,
                    'title' => $live_tv->title,
                    'thumbnail' => apiImage(optional(json_decode($live_tv->thumbnail))->original_image, 'live_tvs'),
                ];
            }) ?? [],
        ];
    }
    public function toggleFavorite(string $type, int $id): string
    {
        $user = auth()->user();
        switch ($type) {
            case 'movie':
                $relation = $user->favoriteMovies();
                break;
            case 'tv_show':
                $relation = $user->favoriteTvShows();
                break;
            case 'live_tv':
                $relation = $user->favoriteLiveTvs();
                break;
            default:
                throw new \InvalidArgumentException("Invalid favorite type: {$type}");
        }

        if ($relation->where('id', $id)->exists()) {
            $relation->detach($id);
            return 'removed';
        } else {
            $relation->attach($id);
            return 'added';
        }
    }
}