<?php

namespace App\Http\Controllers\Admin\Contest;

use App\Enums\ContestStatusEnum;
use App\Exceptions\CustomWebException;
use App\Http\Controllers\Controller;
use App\Models\Contest;
use App\Models\ContestCategory;
use App\Services\ModalIndexQuey;

class ContestHelperController extends Controller
{
    public function getCategories()
    {
        return ModalIndexQuey::get(ContestCategory::query(), select_columns: ['id', 'title as text']);
    }

    public function publish(Contest $contest)
    {
        adminUserHasPermission(permission: 'edit');

        if ($contest->questions()->count() == 0 && $contest->status == ContestStatusEnum::DRAFT) {
            throw new CustomWebException(__('You must add questions first.'));
        }

        $contest->update([
            'status' => ContestStatusEnum::UPCOMING,
        ]);

        return redirect()->back()->withSuccess(__('Contest publish successfully.'));
    }

    public function unPublish(Contest $contest)
    {
        adminUserHasPermission(permission: 'edit');

        if (in_array($contest->status, [ContestStatusEnum::COMPLETED, ContestStatusEnum::RUNNING])) {
            throw new CustomWebException(__('You can not unpublish this contest.'));
        }

        $contest->update([
            'status' => ContestStatusEnum::DRAFT,
        ]);

        return redirect()->back()->withSuccess(__('Contest unpublish successfully.'));
    }
}
