<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\ApiController;
use App\Http\Requests\User\IndexUserRequest;
use App\Http\Requests\User\StoreUserRequest;
use App\Http\Requests\User\UpdateUserRequest;
use App\Http\Resources\User\UserResource;
use App\Models\User;
use App\Services\Access\AccessService;
use App\Services\User\UserService;
use Illuminate\Http\Request;

class UserController extends ApiController
{
    public function __construct(
        protected UserService $service,
        protected AccessService $access
    ) {}

    public function index(IndexUserRequest $request)
    {
        $data = $this->service->list(
            $request->validated(),
            $request->user(),
            $request->attributes->get('tenant_id')
        );

        return $this->successPaginated(
            $data,
            UserResource::class,
            'Data User berhasil diambil'
        );
    }

    public function store(StoreUserRequest $request)
    {
        $data = $this->service->create(
            $request->validated(),
            $request->user()
        );

        return $this->created(
            new UserResource($data),
            'User berhasil dibuat'
        );
    }

    public function show(Request $request, User $user)
    {
        abort_unless(
            $this->access->canManageUser($request->user(), $user, $request->attributes->get('tenant_id')),
            403
        );

        $data = $this->service->show($user);

        return $this->success(
            new UserResource($data),
            'Detail User berhasil diambil'
        );
    }

    public function update(UpdateUserRequest $request, User $user)
    {
        abort_unless(
            $this->access->canManageUser($request->user(), $user, $request->attributes->get('tenant_id')),
            403
        );

        $data = $this->service->update(
            $user,
            $request->validated(),
            $request->user()
        );

        return $this->updated(
            new UserResource($data),
            'User berhasil diupdate'
        );
    }

    public function destroy(Request $request, User $user)
    {
        abort_unless(
            $this->access->canManageUser($request->user(), $user, $request->attributes->get('tenant_id')),
            403
        );

        $this->service->delete($user);

        return $this->deleted('User berhasil dihapus');
    }
}
