<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Business;
use App\Models\ContractTemplate;
use App\Services\AuditService;
use App\Services\SecureFileService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class ContractTemplateDeletionController extends Controller
{
    public function __invoke(ContractTemplate $contractTemplate, SecureFileService $files): RedirectResponse
    {
        $business = Business::firstOrFail();
        abort_unless((int) $contractTemplate->business_id === (int) $business->id, 404);

        $filePath = (string) $contractTemplate->file_path;
        $templateName = (string) $contractTemplate->name;

        DB::transaction(function () use ($contractTemplate): void {
            $template = ContractTemplate::query()->lockForUpdate()->findOrFail($contractTemplate->id);

            if ($template->is_default) {
                throw ValidationException::withMessages([
                    'contract_template' => 'The default contract template cannot be deleted. Set another template as default first.',
                ]);
            }

            if ($template->loans()->exists()) {
                throw ValidationException::withMessages([
                    'contract_template' => 'This contract template has already been used by one or more loans and is preserved for contract history.',
                ]);
            }

            $before = $template->toArray();
            AuditService::record('contract_template.deleted', $template, $before, ['deleted' => true]);
            $template->delete();
        });

        $files->delete($filePath);

        return redirect()
            ->route('admin.contract-templates.index')
            ->with('success', 'Contract template “'.$templateName.'” deleted.');
    }
}
