<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Concerns\FlashesEntityMessage;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Manage\ApproveVerificationRequest;
use App\Http\Requests\Admin\Manage\RejectVerificationRequest;
use App\Models\OwnerVerificationRequest;
use App\Services\Manage\OwnerVerificationService;
use App\Support\ActivityLog\ModelLabel;
use App\Support\OwnerVerification\VerificationChangeFormatter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;

class OwnerVerificationController extends Controller
{
    use FlashesEntityMessage;

    public function __construct(
        private readonly OwnerVerificationService $ownerVerificationService,
    ) {}

    public function show(OwnerVerificationRequest $ownerVerificationRequest): JsonResponse
    {
        $payload = is_array($ownerVerificationRequest->payload) ? $ownerVerificationRequest->payload : [];

        return response()->json([
            'id' => $ownerVerificationRequest->id,
            'action_label' => $ownerVerificationRequest->action->label(),
            'subject_label' => ModelLabel::for($ownerVerificationRequest->subject_type),
            'submitted_by_name' => $ownerVerificationRequest->submittedBy?->profile?->full_name
                ?? $ownerVerificationRequest->submittedBy?->username
                ?? '-',
            'created_at_formatted' => $ownerVerificationRequest->created_at?->translatedFormat('l, d F Y H:i'),
            'changes' => VerificationChangeFormatter::format($payload),
        ]);
    }

    public function approveRequest(
        ApproveVerificationRequest $request,
        OwnerVerificationRequest $ownerVerificationRequest,
    ): RedirectResponse {
        $this->ownerVerificationService->approveRequest(
            $ownerVerificationRequest,
            $request->user(),
            $request->validated('approval_note'),
        );

        $this->flashSuccess('Verifikasi berhasil disetujui.');

        return back(302);
    }

    public function rejectRequest(
        RejectVerificationRequest $request,
        OwnerVerificationRequest $ownerVerificationRequest,
    ): RedirectResponse {
        $this->ownerVerificationService->rejectRequest(
            $ownerVerificationRequest,
            $request->user(),
            $request->validated('reason'),
        );

        $this->flashSuccess('Verifikasi berhasil ditolak.');

        return back(302);
    }
}
