<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\Support\StoreSupportTicketReplyRequest;
use App\Http\Resources\SupportTicketResource;
use App\Models\SupportTicket;
use App\Models\SupportTicketReply;
use App\Support\ApiResponse;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;

class SupportTicketReplyController extends Controller
{
    public function store(StoreSupportTicketReplyRequest $request, SupportTicket $supportTicket)
    {
        Gate::authorize('reply', $supportTicket);

        $user = $request->user();
        $isAdmin = $user->hasRole('admin');

        try {
            DB::beginTransaction();

            $reply = SupportTicketReply::create([
                ...$request->safe()->only(['body', 'attachments']),
                'support_ticket_id' => $supportTicket->id,
                'user_id' => $user->id,
                'is_admin' => $isAdmin,
            ]);

            $ticketUpdates = [];

            if ($supportTicket->status === SupportTicket::STATUS_CLOSED) {
                $ticketUpdates = [
                    'status' => SupportTicket::STATUS_OPEN,
                    'closed_at' => null,
                    'closed_by' => null,
                    'close_reason' => null,
                ];
            } elseif ($isAdmin) {
                $ticketUpdates['status'] = SupportTicket::STATUS_READ;
            } else {
                $ticketUpdates['status'] = SupportTicket::STATUS_UNREAD;
            }

            $ticketUpdates['updated_by'] = Auth::id();

            $supportTicket->update($ticketUpdates);

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

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

        return ApiResponse::created(
            new SupportTicketResource(
                $supportTicket->fresh()->load([
                    'user',
                    'replies' => fn ($query) => $query->with('user')->oldest(),
                ])->loadCount('replies')
            ),
            'پاسخ با موفقیت ثبت شد.'
        );
    }
}
