<?php

namespace App\Http\Controllers;

use App\Models\Professional;
use App\Services\ApplicationManagementService;
use Illuminate\Http\Request;

class ApplicationManagementController extends Controller
{
    public function __construct(private ApplicationManagementService $service) {}

    public function index(Request $request)
    {
        return view('admin.applications', $this->service->index($request->only('q', 'status')));
    }

    public function show(Professional $professional)
    {
        return view('admin.application-detail', ['application' => $this->service->find($professional->id)]);
    }

    public function update(Request $request, Professional $professional)
    {
        $status = $request->validate(['status' => ['required', 'in:approved,declined']])['status'];
        $changed = $professional->status !== $status;

        try {
            $this->service->updateStatus($professional, $status);
        } catch (\Throwable $exception) {
            report($exception);

            return back()->withErrors(['email' => 'The application status was updated, but the notification email could not be sent. Check the mail configuration and logs.']);
        }

        if (! $changed) {
            return back()->with('success', 'The professional application is already '.$status.'. No duplicate email was sent.');
        }

        return back()->with('success', 'Professional application '.$status.' and the applicant was notified by email.');
    }
}
