<?php

namespace App\Services\Nas;

use App\Models\NasMikrotik;
use App\Models\NasOlt;
use App\Models\NasPackageProfile;
use App\Models\NasWebfigDevice;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\ValidationException;

class NasResourceService
{
    private const MODELS = [
        'mikrotik' => NasMikrotik::class,
        'package-profile' => NasPackageProfile::class,
        'olt' => NasOlt::class,
        'webfig' => NasWebfigDevice::class,
    ];

    private const SECRET_FIELDS = [
        'mikrotik' => ['api_password', 'radius_secret'],
        'olt' => ['community', 'auth_password', 'privacy_password'],
        'webfig' => ['password'],
        'package-profile' => [],
    ];

    public function list(string $resource, array $filters, User $actor, ?int $tenantId)
    {
        $model = $this->model($resource);

        return $model::query()
            ->with('tenant:id,tenant_code,tenant_name')
            ->when(! $actor->isMasterAdmin(), fn ($q) => $q->where('tenant_id', $tenantId))
            ->when($actor->isMasterAdmin() && $tenantId, fn ($q) => $q->where('tenant_id', $tenantId))
            ->when(! empty($filters['status']), fn ($q) => $q->where('status', $filters['status']))
            ->when(! empty($filters['connection_type']) && $resource === 'mikrotik', fn ($q) => $q->where('connection_type', $filters['connection_type']))
            ->when(! empty($filters['service_type']) && $resource === 'package-profile', fn ($q) => $q->where('service_type', $filters['service_type']))
            ->when(! empty($filters['search']), function ($q) use ($filters, $resource) {
                $columns = match ($resource) {
                    'mikrotik' => ['name', 'host', 'api_username'],
                    'package-profile' => ['name', 'external_profile_name'],
                    'olt' => ['name', 'host', 'vendor', 'model'],
                    'webfig' => ['name', 'url', 'device_type'],
                };
                $q->where(function ($search) use ($columns, $filters) {
                    foreach ($columns as $index => $column) {
                        $method = $index === 0 ? 'where' : 'orWhere';
                        $search->{$method}($column, 'ILIKE', "%{$filters['search']}%");
                    }
                });
            })
            ->orderBy($filters['sort_by'] ?? 'id', $filters['sort_direction'] ?? 'desc')
            ->paginate($filters['per_page'] ?? 10);
    }

    public function find(string $resource, int $id): Model
    {
        $model = $this->model($resource);

        return $model::with('tenant:id,tenant_code,tenant_name')->findOrFail($id);
    }

    public function create(string $resource, array $data, User $actor, ?int $tenantId): Model
    {
        $data['tenant_id'] = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? $tenantId) : $tenantId;
        if (! $data['tenant_id']) {
            throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
        }
        $data['status'] ??= 'active';
        $model = $this->model($resource);

        return $model::create($data)->load('tenant:id,tenant_code,tenant_name');
    }

    public function update(string $resource, Model $model, array $data, User $actor): Model
    {
        if (! $actor->isMasterAdmin()) {
            unset($data['tenant_id']);
        }
        foreach (self::SECRET_FIELDS[$resource] as $field) {
            if (array_key_exists($field, $data) && blank($data[$field])) {
                unset($data[$field]);
            }
        }
        $model->update($data);

        return $model->fresh()->load('tenant:id,tenant_code,tenant_name');
    }

    public function delete(Model $model): bool
    {
        return $model->delete();
    }

    private function model(string $resource): string
    {
        abort_unless(isset(self::MODELS[$resource]), 404);

        return self::MODELS[$resource];
    }
}
