<?php

namespace App\Services\Roles;

use App\Models\Permission;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PermissionCrudService
{
    public function create(array $payload): Permission
    {
        $data = $this->normalizePayload($payload);

        try {
            return DB::transaction(function () use ($data) {
                return Permission::query()->create($data);
            });
        } catch (\Throwable $e) {
            Log::error('Permission create failed: ' . $e->getMessage());
            throw $e;
        }
    }

    public function update(Permission $permission, array $payload): Permission
    {
        $data = $this->normalizePayload($payload);

        try {
            return DB::transaction(function () use ($permission, $data) {
                $permission->fill($data);
                $permission->save();
                return $permission;
            });
        } catch (\Throwable $e) {
            Log::error('Permission update failed: ' . $e->getMessage());
            throw $e;
        }
    }

    public function delete(Permission $permission): void
    {
        try {
            DB::transaction(function () use ($permission) {
                $permission->delete();
            });
        } catch (\Throwable $e) {
            Log::error('Permission delete failed: ' . $e->getMessage());
            throw $e;
        }
    }

    private function normalizePayload(array $payload): array
    {
        return [
            'name' => trim((string) ($payload['name'] ?? '')),
            'description' => trim((string) ($payload['description'] ?? '')),
        ];
    }
}
