<?php

namespace App\Http\Controllers;

use App\Http\Requests\VideoUpdateRequest;
use App\Models\Video;
use App\Services\UserService;
use App\Services\VideoService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class VideosController extends Controller
{
    protected VideoService $service;
    protected UserService $userService;

    public function __construct(VideoService $service, UserService $userService)
    {
        $this->service = $service;
        $this->userService = $userService;
    }

    public function index(Request $request)
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('viewAny', [Video::class, $organization]);

        return view('pages.videos', [
            'page_title' => 'Quản Lý Video',
            'can_export' => auth()->user()->hasRole('owner') || auth()->user()->hasRole('admin'),
        ]);
    }

    public function users(Request $request): JsonResponse
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('viewAny', [Video::class, $organization]);

        return response()->json($this->userService->getUsersForFilter($this->getOrgHex()));
    }

    public function campaigns(Request $request): JsonResponse
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('viewAny', [Video::class, $organization]);

        return response()->json($this->service->getCampaignsForFilter($this->getOrgHex()));
    }

    public function data(Request $request): JsonResponse
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('viewAny', [Video::class, $organization]);

        $skip = max(0, (int) $request->query('skip', 0));
        $limit = min(max(1, (int) $request->query('limit', 500)), 500);

        return response()->json($this->service->getEligibleBookings($this->getOrgHex(), $skip, $limit));
    }

    public function metrics(Request $request): JsonResponse
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('viewAny', [Video::class, $organization]);

        return response()->json($this->service->getMetrics($this->getOrgHex()));
    }

    public function update(VideoUpdateRequest $request, $id)
    {
        $validated = $request->validated();

        $updated = $this->service->updateVideo($id, $validated, $this->getOrgHex());

        if (!$updated) {
            if ($this->expectsJsonResponse($request)) {
                return response()->json(['message' => 'Không tìm thấy video trong organization hiện tại'], 404);
            }

            return redirect()->back()->with('error', 'Không tìm thấy video trong organization hiện tại');
        }

        if ($this->expectsJsonResponse($request)) {
            return response()->json([
                'id' => strlen($updated->id) === 16 ? bin2hex($updated->id) : $updated->id,
                'url' => $updated->url,
                'status' => $updated->status,
                'spark_ads' => $updated->spark_ads ?? '',
            ]);
        }

        return redirect()->back()->with('success', 'Video được cập nhật thành công');
    }

    public function addRow(Request $request): JsonResponse
    {
        $organization = $request->attributes->get('current_organization');
        $this->authorize('viewAny', [Video::class, $organization]);

        $validated = $request->validate([
            'booking_id' => 'required|string',
        ]);

        $video = $this->service->addVideoRow($validated['booking_id'], $this->getOrgHex());

        if (!$video) {
            return response()->json(['message' => 'Không thể thêm hàng video (đã đạt số lượng tối đa hoặc không tìm thấy booking)'], 400);
        }

        return response()->json($video);
    }

    public function destroy(Request $request, $id)
    {
        $organization = $request->attributes->get('current_organization');

        $video = $this->service->getVideo($id, $this->getOrgHex());

        if (!$video) {
            if ($this->expectsJsonResponse($request)) {
                return response()->json(['message' => 'Không tìm thấy video'], 404);
            }

            return redirect()->back()->with('error', 'Không tìm thấy video trong organization hiện tại');
        }

        $this->authorize('update', [$video, $organization]);

        $deleted = $this->service->deleteVideo($id, $this->getOrgHex());

        if ($this->expectsJsonResponse($request)) {
            return response()->json(['success' => (bool)$deleted]);
        }

        if (!$deleted) {
            return redirect()->back()->with('error', 'Không tìm thấy video trong organization hiện tại');
        }

        return redirect()->back()->with('success', 'Video được xóa thành công');
    }
}
