<?php

namespace App\Http\Resources;

use App\Models\Setting;
use App\Support\Viewer;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * Full video detail for the watch page. The player source is only exposed when
 * the video is unlocked for the current viewer — locked videos return unlock
 * metadata instead of the source URL.
 */
class VideoResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $viewer = Viewer::fromRequest($request);
        $unlocked = $this->isUnlockedFor($viewer->userId, $viewer->guestId);

        $data = [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'description' => $this->description,
            'thumbnail' => $this->thumbnail,
            'duration' => (int) $this->duration,
            'tags' => $this->tags ?? [],
            'is_live' => (bool) $this->is_live,
            'is_exclusive' => (bool) $this->is_exclusive,
            'created_at' => $this->created_at,
            'category' => $this->whenLoaded('category', fn () => [
                'id' => $this->category?->id,
                'name' => $this->category?->name,
                'slug' => $this->category?->slug,
            ]),
            'stats' => [
                'views' => $this->displayViews(),
                'likes' => $this->displayLikes(),
                'comments' => $this->displayComments(),
                'shares' => $this->displayShares(),
            ],
            'uploader' => [
                'name' => Setting::get('channel_name'),
                'avatar' => Setting::get('channel_avatar'),
            ],
            'liked' => (bool) ($this->viewer_liked ?? false),

            // Unlock / lock info
            'is_locked' => (bool) $this->is_locked,
            'unlocked' => $unlocked,
            'unlock' => $this->is_locked ? [
                'required_visits' => (int) $this->required_ad_visits,
                'return_seconds' => (int) $this->return_seconds,
                'completed_visits' => $this->validVisitCountFor($viewer->userId, $viewer->guestId),
                'ad_links' => $this->ad_links ?? [],
            ] : null,
        ];

        // Only reveal playback source + ad-break config when unlocked.
        if ($unlocked) {
            $data['source'] = [
                'type' => $this->source_type,
                'url' => $this->source_url,
            ];
            $data['ad_break'] = [
                'enabled' => $this->effectiveAdBreakInterval() !== null,
                'interval' => $this->effectiveAdBreakInterval(),
            ];
        } else {
            $data['source'] = null;
            $data['ad_break'] = null;
        }

        return $data;
    }
}
