<?php

namespace MintyPHP\Repository\Access;

use MintyPHP\DB;
use MintyPHP\Repository\Support\RepoQuery;
use MintyPHP\Repository\Support\RepositoryArrayHelper;

class PermissionRepository implements PermissionRepositoryInterface
{
    public function list(): array
    {
        $rows = DB::select('select id, `key`, description, active, is_system, created from permissions order by `key` asc');

        return RepositoryArrayHelper::unwrapList($rows, 'permissions');
    }

    public function listActive(): array
    {
        $rows = DB::select(
            'select id, `key`, description, active, is_system, created from permissions where active = 1 order by `key` asc'
        );

        return RepositoryArrayHelper::unwrapList($rows, 'permissions');
    }

    public function listPaged(array $options): array
    {
        $search = trim((string) ($options['search'] ?? ''));
        $allowedOrder = [
            'key' => '`key`',
            'description' => 'description',
            'active' => 'active',
            'created' => 'created',
        ];
        [$limit, $offset] = RepoQuery::sanitizeLimitOffset($options);
        [$order, $dir] = RepoQuery::sanitizeOrder($options, array_keys($allowedOrder), 'key', 'asc');
        $orderBy = $allowedOrder[$order] ?? $allowedOrder['key'];

        $where = [];
        $params = [];
        RepoQuery::addLikeFilter($where, $params, ['permissions.`key`', 'permissions.description'], $search);
        $activeValue = array_key_exists('active', $options) ? $options['active'] : null;
        RepoQuery::addEnumFilter($where, $params, $activeValue, [
            ['aliases' => ['1', 'true', 'active'], 'sql' => 'permissions.active = 1'],
            ['aliases' => ['0', 'false', 'inactive'], 'sql' => 'permissions.active = 0'],
        ]);
        $whereSql = $where ? ' where ' . implode(' and ', $where) : '';

        $total = DB::selectValue('select count(*) from permissions' . $whereSql, ...$params);
        $query = 'select id, `key`, description, active, is_system, created from permissions' . $whereSql .
            ' order by ' . $orderBy . ' ' . $dir . ' limit ? offset ?';
        $queryParams = array_merge($params, [(string) $limit, (string) $offset]);
        $rows = DB::select($query, ...$queryParams);

        return ['rows' => RepositoryArrayHelper::unwrapList($rows, 'permissions'), 'total' => (int) $total];
    }

    public function find(int $id): ?array
    {
        $row = DB::selectOne(
            'select id, `key`, description, active, is_system, created from permissions where id = ? limit 1',
            (string) $id
        );

        return RepositoryArrayHelper::unwrap($row, 'permissions');
    }

    public function findByKey(string $key): ?array
    {
        $row = DB::selectOne(
            'select id, `key`, description, active, is_system, created from permissions where `key` = ? limit 1',
            $key
        );

        return RepositoryArrayHelper::unwrap($row, 'permissions');
    }

    public function create(array $data): ?int
    {
        $key = trim((string) ($data['key'] ?? ''));
        $desc = trim((string) ($data['description'] ?? ''));
        $active = (int) ($data['active'] ?? 1);
        $isSystem = (int) ($data['is_system'] ?? 0);
        $result = DB::insert(
            'insert into permissions (`key`, description, active, is_system, created) values (?,?,?,?,NOW())',
            $key,
            $desc !== '' ? $desc : null,
            (string) $active,
            (string) $isSystem
        );
        return $result ? (int) $result : null;
    }

    public function update(int $id, array $data): bool
    {
        $key = trim((string) ($data['key'] ?? ''));
        $desc = trim((string) ($data['description'] ?? ''));
        $active = (int) ($data['active'] ?? 1);
        $isSystem = (int) ($data['is_system'] ?? 0);
        $result = DB::update(
            'update permissions set `key` = ?, description = ?, active = ?, is_system = ? where id = ?',
            $key,
            $desc !== '' ? $desc : null,
            (string) $active,
            (string) $isSystem,
            (string) $id
        );
        return $result !== false;
    }

    public function delete(int $id): bool
    {
        $result = DB::delete('delete from permissions where id = ?', (string) $id);
        return (bool) $result;
    }
}
