<?php

namespace App\Http\Controllers\Access;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Access\ReviewRoleApplicationRequest;
use App\Http\Requests\Access\StoreRoleApplicationRequest;
use App\Models\RoleApplication;
use App\Services\Access\RoleApplicationService;
use Illuminate\Http\Request;

class RoleApplicationController extends ApiController
{
    public function __construct(protected RoleApplicationService $service) {}

    public function mine(Request $request)
    {
        return $this->success($this->service->mine($request->user()), 'Daftar pengajuan berhasil diambil');
    }

    public function store(StoreRoleApplicationRequest $request)
    {
        return $this->created($this->service->submit($request->validated(), $request->user()), 'Pengajuan berhasil dikirim');
    }

    public function reviewList(Request $request, string $type)
    {
        $filters = $request->validate(['search' => ['nullable', 'string', 'max:100'], 'status' => ['nullable', 'in:pending,approved,rejected'], 'per_page' => ['nullable', 'integer', 'min:1', 'max:100']]);

        return $this->success($this->service->reviewList($type, $filters, $request->user(), $this->tenantId($request)), 'Daftar pengajuan berhasil diambil');
    }

    public function tenantMenuGroupOptions(Request $request)
    {
        return $this->success(
            $this->service->tenantMenuGroupOptions($request->user()),
            'Pilihan Group Menu tenant berhasil diambil'
        );
    }

    public function staffMenuGroupOptions(Request $request)
    {
        return $this->success(
            $this->service->staffMenuGroupOptions($request->user(), $this->tenantId($request)),
            'Pilihan Group Menu staff berhasil diambil'
        );
    }

    public function review(ReviewRoleApplicationRequest $request, RoleApplication $application)
    {
        return $this->updated($this->service->review($application, $request->validated(), $request->user(), $this->tenantId($request)), 'Pengajuan berhasil ditinjau');
    }

    public function linkCustomer(Request $request)
    {
        $data = $request->validate(['customer_id' => ['required', 'integer', 'exists:customers,id'], 'user_id' => ['required', 'integer', 'exists:users,id'], 'relationship' => ['nullable', 'in:owner,family,staff'], 'is_primary' => ['nullable', 'boolean']]);

        return $this->created($this->service->linkCustomer($data, $request->user(), (int) $this->tenantId($request)), 'User berhasil dihubungkan dengan customer');
    }

    private function tenantId(Request $request): ?int
    {
        return $request->attributes->get('tenant_id');
    }
}
