<?php

namespace App\Http\Controllers\Api;

use App\Models\WatchHistory;
use App\Models\Video;
use App\Models\Tv;
use App\Models\Slider;
use App\Models\Episode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class WatchHistoryController extends BaseController
{
    // POST /api/history/update
    // Creates or updates a history entry for the authenticated user.
    public function upsert(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'content_type'    => 'required|in:video,tv,slider,episode',
            'content_id'      => 'required|integer|min:1',
            'watched_seconds' => 'required|integer|min:0',
            'total_seconds'   => 'required|integer|min:0',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator);
        }

        $userId = $request->user()->id;

        $entry = WatchHistory::updateOrCreate(
            [
                'user_id'      => $userId,
                'content_type' => $request->content_type,
                'content_id'   => $request->content_id,
            ],
            [
                'watched_seconds' => $request->watched_seconds,
                'total_seconds'   => $request->total_seconds,
                'completed'       => $request->total_seconds > 0
                                     && ($request->watched_seconds / $request->total_seconds) >= 0.90,
                'watched_at'      => now(),
            ]
        );

        return response()->json([
            'status'  => 'success',
            'message' => 'Watch position saved',
            'data'    => [
                'id'              => $entry->id,
                'watched_seconds' => $entry->watched_seconds,
                'total_seconds'   => $entry->total_seconds,
                'progress'        => $entry->progress,
                'completed'       => $entry->completed,
            ],
        ]);
    }

    // GET /api/history?page=1&per_page=20
    public function index(Request $request)
    {
        $perPage = min((int) $request->get('per_page', 20), 50);

        $entries = WatchHistory::where('user_id', $request->user()->id)
            ->where('completed', false)   // only show in-progress items
            ->orderByDesc('watched_at')
            ->paginate($perPage);

        $data = $entries->map(function (WatchHistory $h) {
            $content = $this->resolveContent($h->content_type, $h->content_id);
            if (!$content) return null;

            return [
                'id'              => $h->id,
                'content_type'    => $h->content_type,
                'content_id'      => $h->content_id,
                'watched_seconds' => $h->watched_seconds,
                'total_seconds'   => $h->total_seconds,
                'progress'        => $h->progress,
                'completed'       => $h->completed,
                'watched_at'      => $h->watched_at?->toISOString(),
                'content'         => $content,
            ];
        })->filter()->values();

        return response()->json([
            'status'  => 'success',
            'message' => 'Watch history retrieved',
            'pagination' => [
                'total_items'   => $entries->total(),
                'current_page'  => $entries->currentPage(),
                'total_pages'   => $entries->lastPage(),
                'items_per_page'=> $entries->perPage(),
            ],
            'data' => $data,
        ]);
    }

    // GET /api/history/position?content_type=video&content_id=5
    // Get resume position for a single piece of content.
    public function getPosition(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'content_type' => 'required|in:video,tv,slider,episode',
            'content_id'   => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator);
        }

        $entry = WatchHistory::where('user_id', $request->user()->id)
            ->where('content_type', $request->content_type)
            ->where('content_id', $request->content_id)
            ->first();

        if (!$entry) {
            return response()->json([
                'status' => 'success',
                'data'   => null,
            ]);
        }

        return response()->json([
            'status' => 'success',
            'data'   => [
                'id'              => $entry->id,
                'watched_seconds' => $entry->watched_seconds,
                'total_seconds'   => $entry->total_seconds,
                'progress'        => $entry->progress,
                'completed'       => $entry->completed,
            ],
        ]);
    }

    // DELETE /api/history/{id}
    public function destroy(Request $request, $id)
    {
        $entry = WatchHistory::where('id', $id)
            ->where('user_id', $request->user()->id)
            ->firstOrFail();

        $entry->delete();

        return response()->json(['status' => 'success', 'message' => 'Removed from history']);
    }

    // DELETE /api/history
    public function clear(Request $request)
    {
        WatchHistory::where('user_id', $request->user()->id)->delete();

        return response()->json(['status' => 'success', 'message' => 'Watch history cleared']);
    }

    // -----------------------------------------------------------------------

    private function resolveContent(string $type, int $id): ?array
    {
        $model = match ($type) {
            'video'   => Video::find($id),
            'tv'      => Tv::find($id),
            'slider'  => Slider::find($id),
            'episode' => Episode::find($id),
            default   => null,
        };

        if (!$model) return null;

        return [
            'id'              => $model->id,
            'title'           => $model->title,
            'thumbnail_image' => $model->thumbnail_image,
            'video_type'      => $model->video_type      ?? null,
            'youtube_url'     => $model->youtube_url     ?? null,
            'other_url'       => $model->other_url       ?? null,
            'video'           => $model->video           ?? null,
            'description'     => $model->description     ?? null,
            'total_views'     => $model->total_views     ?? 0,
            'status'          => $model->status,
        ];
    }
}
