<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\HrSettingResource;
use App\Models\HrSetting;
use App\Support\AccessControl;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class HrSettingsController extends Controller
{
    public function show(Request $request): HrSettingResource
    {
        $user = $request->user();
        abort_unless(AccessControl::allows($user, 'hr', 'read'), 403);

        $settings = HrSetting::query()
            ->with('autoAssignUser')
            ->first();

        if (! $settings) {
            $settings = new HrSetting([
                'provider' => 'internal',
                'is_active' => true,
                'default_sla_days' => 3,
                'allow_employee_requests' => true,
                'require_approval' => true,
                'webhook_secret' => Str::random(40),
            ]);
        }

        return HrSettingResource::make($settings);
    }

    public function update(Request $request): HrSettingResource
    {
        $user = $request->user();
        abort_unless(AccessControl::allows($user, 'hr', 'update'), 403);

        $validated = $request->validate([
            'provider' => ['required', 'string', 'max:60'],
            'is_active' => ['nullable', 'boolean'],
            'api_base_url' => ['nullable', 'string', 'max:255'],
            'api_key' => ['nullable', 'string', 'max:255'],
            'api_secret' => ['nullable', 'string', 'max:255'],
            'webhook_secret' => ['nullable', 'string', 'max:255'],
            'auto_assign_user_id' => ['nullable', 'integer', 'exists:users,id'],
            'default_sla_days' => ['required', 'integer', 'min:1', 'max:365'],
            'allow_employee_requests' => ['nullable', 'boolean'],
            'require_approval' => ['nullable', 'boolean'],
            'meta' => ['nullable', 'array'],
        ]);

        $payload = [
            'provider' => trim((string) $validated['provider']),
            'is_active' => $request->boolean('is_active'),
            'api_base_url' => $this->nullableText($validated['api_base_url'] ?? null),
            'api_key' => $this->nullableText($validated['api_key'] ?? null),
            'api_secret' => $this->nullableText($validated['api_secret'] ?? null),
            'webhook_secret' => $this->nullableText($validated['webhook_secret'] ?? null),
            'auto_assign_user_id' => $validated['auto_assign_user_id'] ?? null,
            'default_sla_days' => (int) $validated['default_sla_days'],
            'allow_employee_requests' => $request->boolean('allow_employee_requests', true),
            'require_approval' => $request->boolean('require_approval', true),
            'meta' => is_array($validated['meta'] ?? null) ? $validated['meta'] : null,
        ];

        if (($payload['webhook_secret'] ?? '') === '') {
            $payload['webhook_secret'] = HrSetting::query()->value('webhook_secret') ?: Str::random(40);
        }

        $settings = HrSetting::query()->first() ?? new HrSetting();
        $settings->fill($payload)->save();

        return HrSettingResource::make($settings->load('autoAssignUser'));
    }

    private function nullableText(mixed $value): ?string
    {
        $value = trim((string) $value);

        return $value === '' ? null : $value;
    }
}
