<?php

namespace App\Modules\CommercialInvoice\Domain;

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

class IndexCommercialInvoice implements StorageCriteria
{

    public function __construct(
        private IdCommercialInvoice $id
    ) {}

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

    protected function query()
    {
        $select = CommercialInvoice::select('`ci`');
        $table = CommercialInvoice::table();
        return DB::select(
            "SELECT $select
            FROM `$table` `ci`
            WHERE `ci`.`Id_CommercialInvoice` = ?
            AND `ci`.`CommercialInvoice_Status` <> 0",
            [
                $this->id->value()
            ]
        );
    }

    protected function analize($data)
    {
        if (!count($data)) {
            throw new CommercialInvoiceNotFound();
        }
        return CommercialInvoice::fromDTO($data[0]);
    }
}
