<?php
namespace App\Http\Resources;

use App\Models\Movie;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Models\Star;
use App\Models\ReviewLikes;
use Illuminate\Support\Facades\Auth;

class MovieResource extends JsonResource
{
    public function toArray($request)
    {
        $userId = Auth::id();

        // Collect all star IDs (cast, director, writer)
        $castIds = json_decode($this->stars) ?? [];
        $directorIds = json_decode($this->director) ?? [];
        $writerIds = json_decode($this->writer) ?? [];
        $allStarIds = collect($castIds)->merge($directorIds)->merge($writerIds)->unique()->filter()->values();

        // Fetch all stars in one query
        $stars = Star::whereIn('id', $allStarIds)->get()->keyBy('id');

        // Helper to format a star
        $formatStar = fn($star) => [
            'id' => $star->id,
            'name' => $star->star_name,
            'image' => apiImageFromJson($star->star_image, 'original_image', 'stars'),
        ];

        // Format cast, director, writer
        $cast = collect($castIds)->map(fn($id) => $stars[$id] ?? null)->filter()->map($formatStar)->values();
        $directors = collect($directorIds)->map(fn($id) => $stars[$id] ?? null)->filter()->map($formatStar)->values();
        $writers = collect($writerIds)->map(fn($id) => $stars[$id] ?? null)->filter()->map($formatStar)->values();

        // Format reviews (limit to 10)
        $reviews = $this->reviews()->with('user')->latest()->limit(10)->get()->map(function ($item) use ($userId) {
            $likes = ReviewLikes::where('review_id', $item->id)->get();
            return [
                'id' => $item->id,
                'review' => $item->review,
                'rating' => $item->rating ?? null,
                'created_at' => $item->created_at->format('d M Y'),
                'updated_at' => $item->updated_at->format('d M Y'),
                'user' => $item->user ? [
                    'id' => $item->user->id,
                    'user_name' => trim($item->user->first_name . ' ' . $item->user->last_name),
                    'email' => $item->user->email,
                    'profile_image' => apiImageFromJson($item->user->image, 'original_image', 'users'),
                ] : null,
                'total_likes' => $likes->count(),
                'is_liked' => $likes->contains('user_id', $userId),
            ];
        });

        return [
            'id' => $this->id,
            'name' => $this->title,
            'slug' => $this->slug,
            'description' => $this->description,
            'release_date' => $this->release,
            'status' => $this->status,
            'is_free' => $this->is_free,
            'runtime' => runtime($this->runtime),
            'imdb_rating ' => $this->imdb_rating,
            'thumbnail' => apiImageFromJson($this->thumbnail, 'original_image', 'movies'),
            'cover_photo' => apiImageFromJson($this->cover_photo, 'original_image', 'movies'),
            'cast' => $cast,
            'director' => $directors,
            'writer' => $writers,
            'related_movies' => Movie::where('status', 1)
                ->where('video_type', $this->video_type)
                ->where('genre', $this->genre) // Exact match for genre string
                ->where('id', '!=', $this->id)
                ->limit(6)
                ->get()
                ->map(function ($movie) {
                    return [
                        'id' => $movie->id,
                        'name' => $movie->title,
                        'slug' => $movie->slug,
                        'thumbnail' => apiImageFromJson($movie->thumbnail, 'original_image', 'movies'),
                    ];
                }),
        ];
    }
}