<?php

namespace App\Http\Controllers\Admin\Users;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\UpdateStatusRequest;
use App\Http\Requests\Admin\Users\AdministratorRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\User;
use App\Services\Admin\Users\AdministratorService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class AdministratorController extends Controller
{
    public function __construct(
        private readonly AdministratorService $service,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/users/administrators/index', [
            'administrators' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                gender: $request->validated('gender'),
            ),
            'filters' => $request->only(['gender']),
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('admin/users/administrators/create', [
            'roles' => $this->service->availableRoles(),
        ]);
    }

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

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Administrator berhasil ditambahkan.']);

        return to_route('admin.users.administrators.index');
    }

    public function edit(User $user): Response
    {
        $user->load(['profile', 'roles']);

        return Inertia::render('admin/users/administrators/edit', [
            'user' => $user,
            'roles' => $this->service->availableRoles(),
        ]);
    }

    public function update(AdministratorRequest $request, User $user): RedirectResponse
    {
        $this->service->update($user, $request->validated());

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Administrator berhasil diperbarui.']);

        return to_route('admin.users.administrators.index');
    }

    public function destroy(User $user): RedirectResponse
    {
        $this->service->delete($user);

        return Inertia::flash('toast', ['type' => 'success', 'message' => 'Administrator berhasil dihapus.'])->back();
    }

    public function resetPassword(User $user): RedirectResponse
    {
        $this->service->resetPassword($user);

        return Inertia::flash('toast', ['type' => 'success', 'message' => 'Kata sandi berhasil direset.'])->back();
    }

    public function updateUserStatus(UpdateStatusRequest $request, User $user): RedirectResponse
    {
        $this->service->updateUserStatus($user, $request->boolean('is_active'));

        return Inertia::flash('toast', ['type' => 'success', 'message' => 'Status akun berhasil diperbarui.'])->back();
    }
}
