<?php

namespace App\Modules\ApplicationScope\Domain;

use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use Illuminate\Support\Facades\DB;

class ListApplicationScopesByApplication implements StorageCriteria
{
    public function __construct(
        private int $idApplication,
        private bool $lockInShare = false
    ) {}

    public function run()
    {
        return $this->analyze($this->query());
    }

    protected function query()
    {
        $lock = $this->lockInShare ? ' LOCK IN SHARE MODE' : '';

        return DB::select("
            SELECT
                aps.Id_ApplicationScope,
                aps.ApplicationScope_Status,
                s.Id_Scope,
                s.Scope_Name,
                s.Scope_Status
            FROM t_application_scope aps
            INNER JOIN t_scope s
                ON s.Id_Scope = aps.Id_Scope
            WHERE aps.Id_Application = ? AND aps.ApplicationScope_Status = 2
            $lock
        ", [
            $this->idApplication
        ]);
    }

    protected function analyze($data)
    {
        if (!count($data)) {
            return [];
        }

        return array_map(
            fn($row) => new ApplicationScopeDTO(
                $row->Id_ApplicationScope,
                $row->ApplicationScope_Status,
                $row->Id_Scope,
                $row->Scope_Name,
                $row->Scope_Status
            ),
            $data
        );
    }
}
