<?php

namespace Modules\Roles\Services;

use App\Models\ActivityLogModel;
use App\Models\PermissionModel;

class PermissionService
{
    protected PermissionModel $permissions;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->permissions = new PermissionModel();
        $this->activity     = new ActivityLogModel();
    }

    public function createCustom(array $input, ?int $actingUserId): array
    {
        $group = strtolower(trim($input['group']));
        $action = strtolower(trim($input['action']));
        $slug  = "{$group}.{$action}";

        $data = [
            'group'      => $group,
            'slug'       => $slug,
            'label'      => $input['label'] ?: ucfirst($action) . ' ' . ucfirst($group),
            'is_system'  => 0,
            'created_at' => date('Y-m-d H:i:s'),
        ];

        if (! $this->permissions->insert($data, true)) {
            return ['success' => false, 'errors' => $this->permissions->errors()];
        }

        $id = $this->permissions->getInsertID();
        $this->activity->log('permissions', 'created', $actingUserId, "Created permission {$slug}", (string) $id);

        return ['success' => true, 'id' => $id];
    }

    public function delete(int $id, ?int $actingUserId): array
    {
        $permission = $this->permissions->find($id);
        if (! $permission) {
            return ['success' => false, 'error' => 'Permission not found.'];
        }
        if ($permission['is_system']) {
            return ['success' => false, 'error' => 'System permissions cannot be deleted.'];
        }

        $this->permissions->delete($id);
        $this->activity->log('permissions', 'deleted', $actingUserId, "Deleted permission {$permission['slug']}", (string) $id);

        return ['success' => true];
    }
}
