<?php

declare(strict_types=1);

namespace App\Http\Controllers\Project;

use App\Http\Controllers\Concerns\AuthorizesProjectAccess;
use App\Http\Controllers\Controller;
use App\Http\Requests\Rating\StoreRatingRequest;
use App\Models\MediaItem;
use App\Models\Project;
use App\Models\Rating;
use App\Support\ApiResponse;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ProjectRatingController extends Controller
{
    use AuthorizesProjectAccess;

    public function store(StoreRatingRequest $request, Project $project)
    {
        $this->authorizeProjectAccess($project);

        try {
            DB::beginTransaction();

            if ($request->filled('media_item_id')) {
                $mediaItem = MediaItem::query()
                    ->where('project_id', $project->id)
                    ->where('status', MediaItem::STATUS_APPROVED)
                    ->findOrFail($request->integer('media_item_id'));

                $rateableType = MediaItem::class;
                $rateableId = $mediaItem->id;
            } else {
                $rateableType = Project::class;
                $rateableId = $project->id;
            }

            $rating = Rating::updateOrCreate(
                [
                    'user_id' => Auth::id(),
                    'rateable_type' => $rateableType,
                    'rateable_id' => $rateableId,
                ],
                [
                    'score' => $request->scoreValue(),
                    'comment' => $request->input('comment'),
                ]
            );

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();

            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return ApiResponse::success([
            'id' => $rating->id,
            'rate' => (int) $rating->score,
            'score' => (int) $rating->score,
            'rateable_type' => $rateableType,
            'rateable_id' => $rateableId,
        ]);
    }
}
