<?php

namespace App\Modules\HR\Contracts\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Contracts\Models\ContractTemplate;
use App\Modules\HR\Contracts\Repositories\ContractTemplateRepository;
use App\Modules\HR\Contracts\Requests\ContractTemplateRequest;
use App\Modules\HR\Contracts\Services\ContractTemplateService;
use App\Modules\HR\Contracts\Support\ContractType;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class ContractTemplateController extends Controller
{
    public function __construct(
        private readonly ContractTemplateRepository $templates,
        private readonly ContractTemplateService $service,
    ) {}

    public function index(): View
    {
        return view('pages.hr.contract-templates.index', [
            'templates' => $this->templates->list($this->tenantId()),
        ]);
    }

    public function create(): View
    {
        return view('pages.hr.contract-templates.create', ['types' => $this->types()]);
    }

    public function store(ContractTemplateRequest $request): RedirectResponse
    {
        $this->service->create($this->tenantId(), $request->validated());

        return redirect()->route('hr.contract-templates.index')->with('status', __('contracts.templates.created'));
    }

    public function edit(ContractTemplate $contractTemplate): View
    {
        $this->ensureTenant($contractTemplate);

        return view('pages.hr.contract-templates.edit', compact('contractTemplate') + ['types' => $this->types()]);
    }

    public function update(ContractTemplateRequest $request, ContractTemplate $contractTemplate): RedirectResponse
    {
        $this->ensureTenant($contractTemplate);
        $this->service->update($contractTemplate, $request->validated());

        return redirect()->route('hr.contract-templates.index')->with('status', __('contracts.templates.updated'));
    }

    private function tenantId(): int
    {
        return (int) auth()->user()->tenant_id;
    }

    private function ensureTenant(ContractTemplate $template): void
    {
        abort_unless((int) $template->tenant_id === $this->tenantId(), 404);
    }

    /** @return array<string, string> */
    private function types(): array
    {
        return array_combine(ContractType::all(), array_map(fn ($type) => __('contracts.types.'.$type), ContractType::all()));
    }
}
