<?php

namespace App\Modules\Shared\Infraestructure;

use App\Modules\Shared\Exceptions\InvalidRequestException;
use Illuminate\Support\Facades\DB;

class RequestChecker
{

    public static function requestSelect($query, array $data, $domain = null)
    {
        list($responseData, $metadata) = self::queryData($query, $data, $domain);
        return $responseData;
    }

    public static function requestInsert($query, array $data, $domain = null)
    {
        list($responseData, $metadata) = self::queryData($query, $data, $domain);
        return self::generateResponse($query, $metadata, ['Id' => $metadata[0]->Response_Id], $domain);
    }

    public static function requestUpdate($query, array $data, $domain = null)
    {
        list($responseData, $metadata) = self::queryData($query, $data, $domain);
        return self::generateResponse($query, $metadata, null, $domain);
    }

    public static function queryData($query, $data, $domain)
    {
        $responseData = DB::select($query, $data);
        $q = 'SELECT @sts as Response_Status, @cod as Response_Code, @msg as Response_Message, @id as Response_Id';
        $metadata = DB::select($q);
        if ($metadata[0]->Response_Status != 200) {
            throw new InvalidRequestException(self::generateResponse($query, $metadata, null, $domain));
        }
        return [$responseData, $metadata];
    }

    public static function generateResponse(string $query, array $metadata, $data, $domain = null)
    {
        return [
            "Response_Status"           => $metadata[0]->Response_Status,
            "Response_Code"             => $metadata[0]->Response_Code,
            "Response_Domain"           => $domain ?? 'global',
            "Response_Message"          => $metadata[0]->Response_Message,
            "Response_Data"             => $data,
            "Response_Error_Message"    => $metadata[0]->Response_Status != 200 ? $metadata[0]->Response_Message : '',
            "Response_Error_Reason"     => $metadata[0]->Response_Status != 200 ? $metadata[0]->Response_Message : '',
        ];
    }
}
