<?php

namespace GriffinForms\Includes\Migration;

class MigrationResult
{
    public ?int $griffinforms_form_id = null;

    /** @var array<int, array<string, mixed>> */
    public array $field_id_map = [];

    /** @var array<int, array<string, string>> */
    public array $migrated = [];

    /** @var array<int, array<string, string>> */
    public array $skipped = [];

    /** @var array<int, array<string, string>> */
    public array $errors = [];

    public bool $success = true;

    public function setGriffinFormsFormId(?int $form_id): self
    {
        $this->griffinforms_form_id = $form_id !== null ? absint($form_id) : null;
        return $this;
    }

    public function addMigrated(string $label, string $type): self
    {
        $this->migrated[] = [
            'label' => sanitize_text_field($label),
            'type' => sanitize_key($type),
        ];

        return $this;
    }

    public function addSkipped(string $label, string $reason): self
    {
        $this->skipped[] = [
            'label' => sanitize_text_field($label),
            'reason' => sanitize_text_field($reason),
        ];

        return $this;
    }

    public function addError(string $message): self
    {
        $this->errors[] = [
            'message' => sanitize_text_field($message),
        ];
        $this->success = false;

        return $this;
    }

    public function merge(MigrationResult $other): self
    {
        if ($this->griffinforms_form_id === null && $other->griffinforms_form_id !== null) {
            $this->griffinforms_form_id = $other->griffinforms_form_id;
        }

        $this->migrated = array_merge($this->migrated, $other->migrated);
        $this->skipped = array_merge($this->skipped, $other->skipped);
        $this->errors = array_merge($this->errors, $other->errors);

        if (!$other->success || !empty($other->errors)) {
            $this->success = false;
        }

        return $this;
    }
}
