<?php

namespace App\Http\Controllers;

use App\Repos\ColoredRepo;
use App\Repos\CreditRepo;
use App\Repos\PageRepo;
use App\Services\ResponseService;
use App\Services\ValidationService;
use Illuminate\Http\Request;
use Throwable;

class ColoredController extends Controller
{
    public function upsert(Request $request)
    {
        try {
            $rules = [
                'pageId' => ['required', 'exists:pages,id'],
                'photo' => ['required', 'url'],
                'preview' => ['required', 'url'],
            ];
            ValidationService::validate($request->all(), $rules);
            $user = $request->user();
            $page = PageRepo::findOrFailById($request->pageId);
            $isColored = $page->is_colored;
            $isOwner = $page->is_owner;
            $colored = [
                'photo' => $request->photo,
                'preview' => $request->preview,
            ];
            ColoredRepo::updateOrCreateByUserIdAndPageId(
                $user->id,
                $request->pageId,
                $colored
            );
            if (!$isColored && !$isOwner) {
                CreditRepo::decrementByUserId($user->id, 'public_page');
            }
            if (!$isColored) {
                PageRepo::incrementColoredCount($page->id);
            }
            return ResponseService::ok($colored);
        } catch (Throwable $error) {
            return ResponseService::handleError($error);
        }
    }

    public function paginate(Request $request)
    {
        try {
            $query = $request->query();
            $rules = [
                'page' => ['required', 'integer', 'min:1'],
                'search' => ['nullable', 'string'],
            ];
            ValidationService::validate($query, $rules);
            $paginate = ColoredRepo::paginate(
                $request->query('page'),
                $request->query('search'),
            );
            return ResponseService::ok($paginate);
        } catch (Throwable $error) {
            return ResponseService::handleError($error);
        }
    }
}
