<?php

namespace App\Modules\HR\Employees\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Employees\Requests\CreateEmployeeUserAccountRequest;
use App\Modules\HR\Employees\Requests\LinkEmployeeUserAccountRequest;
use App\Modules\HR\Employees\Services\EmployeeUserAccountService;
use Illuminate\Http\RedirectResponse;

class EmployeeUserAccountController extends Controller
{
    public function __construct(
        private readonly EmployeeUserAccountService $accounts,
    ) {}

    public function store(CreateEmployeeUserAccountRequest $request, Employee $employee): RedirectResponse
    {
        $tenant = auth()->user()?->tenant;
        abort_if($tenant === null, 403);

        $this->accounts->createAccount(
            $tenant,
            $employee,
            (string) $request->validated('password'),
            array_map('intval', $request->validated('role_ids')),
        );

        return redirect()
            ->route('hr.employees.edit', $employee)
            ->with('status', __('employees.user_account.flash.created'));
    }

    public function link(LinkEmployeeUserAccountRequest $request, Employee $employee): RedirectResponse
    {
        $tenant = auth()->user()?->tenant;
        abort_if($tenant === null, 403);

        $this->accounts->linkExisting(
            $tenant,
            $employee,
            (int) $request->validated('user_id'),
        );

        return redirect()
            ->route('hr.employees.edit', $employee)
            ->with('status', __('employees.user_account.flash.linked'));
    }

    public function unlink(Employee $employee): RedirectResponse
    {
        $user = auth()->user();
        abort_if($user === null, 403);
        abort_unless(
            $user->can('employees.update', $employee) && $user->can('settings.users.assign_roles'),
            403,
        );

        $tenant = $user->tenant;
        abort_if($tenant === null, 403);

        $this->accounts->unlink($tenant, $employee);

        return redirect()
            ->route('hr.employees.edit', $employee)
            ->with('status', __('employees.user_account.flash.unlinked'));
    }
}
