<?php

namespace App\Workflows\Services;

use App\Workflows\Models\FormDefinition;
use App\Workflows\Models\WorkflowTemplate;
use Illuminate\Support\Facades\DB;

/**
 * Clones workflow templates to create editable drafts
 */
class TemplateCloner
{
    /**
     * Clone a published template to create a new draft version
     */
    public function cloneToDraft(WorkflowTemplate $template): WorkflowTemplate
    {
        return DB::transaction(function () use ($template) {
            // Create new template
            $newTemplate = $template->replicate([
                'status',
                'version',
                'published_at',
                'is_active',
            ]);

            $newTemplate->status = 'draft';
            $newTemplate->version = 1; // Reset version for draft
            $newTemplate->published_at = null;
            $newTemplate->is_active = false;
            $newTemplate->save();

            // Clone step templates
            foreach ($template->stepTemplates as $stepTemplate) {
                $newStepTemplate = $stepTemplate->replicate(['workflow_template_id', 'is_locked']);
                $newStepTemplate->workflow_template_id = $newTemplate->id;
                $newStepTemplate->is_locked = false; // Unlock for editing

                // Clone form definition if present
                if ($stepTemplate->form_definition_id) {
                    $newFormDefinition = $this->cloneFormDefinition($stepTemplate->formDefinition);
                    $newStepTemplate->form_definition_id = $newFormDefinition->id;
                }

                $newStepTemplate->save();
            }

            return $newTemplate;
        });
    }

    /**
     * Clone a form definition (deep copy for versioning)
     */
    private function cloneFormDefinition(FormDefinition $formDefinition): FormDefinition
    {
        $newFormDefinition = $formDefinition->replicate();
        $newFormDefinition->name = $formDefinition->name.' (Copy)';
        $newFormDefinition->save();

        // TODO: If Relaticle Custom Fields requires deep copying of field definitions,
        // implement export/import functionality here and store in form_definition snapshot

        return $newFormDefinition;
    }
}
