<?php

namespace App\Domains\Leads\Actions;

use App\Domains\Leads\Models\Pipeline;
use App\Domains\Leads\Models\PipelineStage;
use App\Domains\Tenancy\Models\Tenant;

class CreateDefaultPipelineAction
{
    public function execute(Tenant $tenant): Pipeline
    {
        $pipeline = Pipeline::query()->create([
            'tenant_id' => $tenant->getKey(),
            'name' => 'Default Sales Pipeline',
            'is_default' => true,
        ]);

        $stages = [
            ['name' => 'New Lead', 'color' => 'slate', 'is_closed' => false, 'win_flag' => false, 'loss_flag' => false],
            ['name' => 'Contacted', 'color' => 'blue', 'is_closed' => false, 'win_flag' => false, 'loss_flag' => false],
            ['name' => 'Interested', 'color' => 'amber', 'is_closed' => false, 'win_flag' => false, 'loss_flag' => false],
            ['name' => 'Waiting Reply', 'color' => 'violet', 'is_closed' => false, 'win_flag' => false, 'loss_flag' => false],
            ['name' => 'Quote Sent', 'color' => 'indigo', 'is_closed' => false, 'win_flag' => false, 'loss_flag' => false],
            ['name' => 'Order Pending', 'color' => 'orange', 'is_closed' => false, 'win_flag' => false, 'loss_flag' => false],
            ['name' => 'Won', 'color' => 'green', 'is_closed' => true, 'win_flag' => true, 'loss_flag' => false],
            ['name' => 'Lost', 'color' => 'red', 'is_closed' => true, 'win_flag' => false, 'loss_flag' => true],
        ];

        foreach ($stages as $index => $stage) {
            PipelineStage::query()->create([
                'tenant_id' => $tenant->getKey(),
                'pipeline_id' => $pipeline->getKey(),
                'name' => $stage['name'],
                'position' => $index + 1,
                'color' => $stage['color'],
                'is_closed' => $stage['is_closed'],
                'win_flag' => $stage['win_flag'],
                'loss_flag' => $stage['loss_flag'],
            ]);
        }

        return $pipeline;
    }
}
