<?php

namespace App\Models\DTO;

use Illuminate\Contracts\Support\Responsable;
use Illuminate\Cookie\CookieJar;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Cookie;
use Exception;

class ResponseData implements Responsable
{
    public int $success = 1;
    public string $code = "200";
    public string $message = "";
    public CookieJar|Cookie|null $cookie = null;

    public static function fromException(Exception $e): static
    {
        $res = new static();
        $res->success = 0;
        $res->code = $e->getCode();
        $res->message = $e->getMessage();
        return $res;
    }

    public function cookie($cookie): CookieJar|Cookie
    {
        return $this->cookie = $cookie;
    }

    public function __set($name, $value)
    {
        $this->{$name} = $value;
    }

    public function __get($name): mixed
    {
        return ($this->{$name} ?? null);
    }

    public function toResponse($request): JsonResponse
    {
        $response = response()->json($this);
        if ($this->cookie) {
            $response->cookie($this->cookie);
        }
        return $response;
    }
}
