<?php

namespace App\Workflows\Services;

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

/**
 * Publishes workflow templates making them immutable
 */
class TemplatePublisher
{
    public function __construct(
        private RequiredStepsValidator $validator
    ) {}

    /**
     * Publish a draft template
     *
     * @throws InvalidArgumentException
     */
    public function publish(WorkflowTemplate $template): void
    {
        if (! $template->isDraft()) {
            throw new InvalidArgumentException('Only draft templates can be published');
        }

        // Validate required steps
        $this->validator->validate($template);

        DB::transaction(function () use ($template) {
            // Lock all step templates
            $template->stepTemplates()->update(['is_locked' => true]);

            // Set version to max + 1 for this (org, subject_type) combination
            $maxVersion = WorkflowTemplate::where('org_id', $template->org_id)
                ->where('subject_type', $template->subject_type)
                ->max('version') ?? 0;

            // Update template
            $template->update([
                'status' => 'published',
                'version' => $maxVersion + 1,
                'published_at' => now(),
                'is_active' => true,
            ]);

            // Deactivate other templates for this subject type in the org
            WorkflowTemplate::where('org_id', $template->org_id)
                ->where('subject_type', $template->subject_type)
                ->where('id', '!=', $template->id)
                ->update(['is_active' => false]);
        });
    }
}
