<?php

namespace App\Modules\HR\Organization\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Departments\Repositories\DepartmentRepository;
use App\Modules\HR\Organization\DTOs\TeamWriteData;
use App\Modules\HR\Organization\Models\Team;
use App\Modules\HR\Organization\Repositories\SectionRepository;
use App\Modules\HR\Organization\Requests\StoreTeamRequest;
use App\Modules\HR\Organization\Requests\UpdateTeamRequest;
use App\Modules\HR\Organization\Services\TeamService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class TeamPageController extends Controller
{
    public function __construct(private readonly TeamService $service, private readonly DepartmentRepository $departments, private readonly SectionRepository $sections) {}

    public function index(\Illuminate\Http\Request $request): View
    {
        return view('pages.hr.organization.index', ['records' => $this->service->paginateForIndex($request), 'entity' => 'team', 'route' => 'teams']);
    }

    public function create(): View
    {
        return view('pages.hr.organization.create', array_merge(['entity' => 'team', 'route' => 'teams'], ['departmentOptions' => $this->departments->listForSelect(), 'sectionOptions' => $this->sections->listForSelect()]));
    }

    public function store(StoreTeamRequest $request): RedirectResponse
    {
        $this->service->store(TeamWriteData::fromValidated($request->validated()));

        return redirect()->route('hr.teams.index')->with('status', __('organization.flash.created'));
    }

    public function edit(Team $team): View
    {
        return view('pages.hr.organization.edit', array_merge(['record' => $team, 'entity' => 'team', 'route' => 'teams'], ['departmentOptions' => $this->departments->listForSelect(), 'sectionOptions' => $this->sections->listForSelect()]));
    }

    public function update(UpdateTeamRequest $request, Team $team): RedirectResponse
    {
        $this->service->update($team, TeamWriteData::fromValidated($request->validated()));

        return redirect()->route('hr.teams.index')->with('status', __('organization.flash.updated'));
    }

    public function deactivate(Team $team): RedirectResponse
    {
        $this->authorize('deactivate', $team);
        $this->service->deactivate($team);

        return back()->with('status', __('organization.flash.deactivated'));
    }
}
