<?php

declare(strict_types=1);

namespace App\Models;

/**
 * Result of POST /karvipartner/contracts (Create contract API).
 */
final class ContractCreateResult
{
    public function __construct(
        public readonly bool $success,
        public readonly string $message,
        public readonly ?array $contract = null,
        public readonly ?array $apiResponse = null,
        public readonly ?array $apiContract = null,
        public readonly int $httpStatus = 0,
        public readonly ?string $errorCode = null,
    ) {
    }

    public static function ok(
        string $message,
        array $apiResponse,
        array $apiContract,
        ?array $localContract = null,
        int $httpStatus = 200
    ): self {
        return new self(
            success: true,
            message: $message,
            contract: $localContract,
            apiResponse: $apiResponse,
            apiContract: $apiContract,
            httpStatus: $httpStatus,
        );
    }

    public static function fail(
        string $message,
        ?array $apiResponse = null,
        int $httpStatus = 400,
        ?string $errorCode = null
    ): self {
        return new self(
            success: false,
            message: $message,
            apiResponse: $apiResponse,
            httpStatus: $httpStatus,
            errorCode: $errorCode,
        );
    }

    public function id(): ?int
    {
        $id = $this->apiContract['id'] ?? null;

        return is_numeric($id) ? (int)$id : null;
    }

    public function signToken(): string
    {
        return trim((string)($this->apiContract['sign_token'] ?? ''));
    }

    public function signUrl(): string
    {
        return trim((string)($this->apiContract['sign_url'] ?? ''));
    }

    public function contractStatus(): string
    {
        return trim((string)($this->apiContract['contract_status'] ?? ''));
    }

    public function createdAt(): string
    {
        return trim((string)($this->apiContract['created_at'] ?? ''));
    }

    public function updatedAt(): string
    {
        return trim((string)($this->apiContract['updated_at'] ?? ''));
    }

    public function restaurantName(): string
    {
        return trim((string)($this->apiContract['restaurant_name'] ?? ($this->contract['restaurant_name'] ?? '')));
    }

    public function ownerName(): string
    {
        $owner = $this->apiContract['owner_name'] ?? ($this->contract['owner_name'] ?? '');
        if (is_array($owner)) {
            return implode(', ', array_filter(array_map('trim', $owner)));
        }

        return trim((string)$owner);
    }

    public function email(): string
    {
        return trim((string)($this->apiContract['email'] ?? ($this->contract['email'] ?? '')));
    }
}
