<?php

namespace App\Services\SlugScoped;

use Illuminate\Database\Eloquent\Model;

class SlugConflictResult
{
    public const STATE_AVAILABLE = 'available';
    public const STATE_RESTORABLE = 'restorable';
    public const STATE_CONFLICT_LIVE = 'conflict_live';

    public function __construct(
        public readonly string $state,
        public readonly ?Model $live = null,
        public readonly ?Model $trashed = null,
        public readonly ?string $slug = null,
        public readonly ?string $franchiseeId = null,
    ) {
    }

    public function isAvailable(): bool
    {
        return $this->state === self::STATE_AVAILABLE;
    }

    public function isRestorable(): bool
    {
        return $this->state === self::STATE_RESTORABLE;
    }

    public function hasLiveConflict(): bool
    {
        return $this->state === self::STATE_CONFLICT_LIVE;
    }

    public function toConflictArray(): array
    {
        $payload = [
            'slug' => $this->slug,
            'franchisee_id' => $this->franchiseeId,
        ];

        if ($this->live) {
            $payload['live'] = $this->summarizeModel($this->live);
        }

        if ($this->trashed) {
            $payload['trashed'] = $this->summarizeModel($this->trashed, true);
        }

        return $payload;
    }

    private function summarizeModel(Model $model, bool $includeDeletedAt = false): array
    {
        $summary = [
            'id' => $model->getKey(),
            'title' => $model->title ?? $model->name ?? null,
            'slug' => $model->slug ?? null,
            'updated_at' => $model->updated_at?->toIso8601String(),
        ];

        if ($includeDeletedAt) {
            $summary['deleted_at'] = $model->deleted_at?->toIso8601String();
        }

        return $summary;
    }
}
