<?php

declare(strict_types=1);

namespace Database\Seeders;

use PDO;

/**
 * MarketingSeeder
 *
 * Seeds the 5 automation rules named explicitly in the Phase 4 brief
 * (Welcome Email, Follow-up Email, Appointment Reminder, Birthday
 * Email, Re-engagement Campaign), a starter set of email templates
 * they use, and a couple of sample audience segments demonstrating the
 * "Filtered Audience" feature.
 */
final class MarketingSeeder implements SeederInterface
{
    public function run(PDO $pdo): void
    {
        $this->seedTemplates($pdo);
        $this->seedAutomationRules($pdo);
        $this->seedAudienceSegments($pdo);
    }

    private function seedTemplates(PDO $pdo): void
    {
        $homecareId = (int) $pdo->query("SELECT id FROM business_lines WHERE slug='homecare'")->fetchColumn();

        $templates = [
            [
                'name' => 'Welcome — New Lead', 'category' => 'homecare',
                'subject' => 'Welcome to A&B Homecare, {{first_name}}!',
                'body_html' => '<p>Hi {{first_name}},</p><p>Thank you for reaching out to A&B Homecare Services. A member of our team will be in touch shortly to discuss your care needs.</p>',
            ],
            [
                'name' => 'Follow-up — Still Interested?', 'category' => 'general',
                'subject' => 'Still thinking it over, {{first_name}}?',
                'body_html' => '<p>Hi {{first_name}},</p><p>We wanted to follow up on your recent inquiry — happy to answer any questions or set up a time to talk.</p>',
            ],
            [
                'name' => 'Birthday Greeting', 'category' => 'general',
                'subject' => 'Happy Birthday from all of us, {{first_name}}! 🎉',
                'body_html' => '<p>Hi {{first_name}},</p><p>Wishing you a wonderful birthday from the whole A&B team!</p>',
            ],
            [
                'name' => 'Re-engagement — We Miss You', 'category' => 'general',
                'subject' => "It's been a while, {{first_name}}",
                'body_html' => '<p>Hi {{first_name}},</p><p>We noticed it\'s been some time since your last visit. Is there anything we can help with?</p>',
            ],
        ];

        $stmt = $pdo->prepare(
            'INSERT INTO email_templates (business_line_id, name, category, subject, body_html, created_at, updated_at)
             VALUES (:bl, :name, :category, :subject, :body, NOW(), NOW())'
        );

        $ids = [];
        foreach ($templates as $t) {
            $exists = $pdo->prepare('SELECT id FROM email_templates WHERE name = :name');
            $exists->execute(['name' => $t['name']]);
            $existingId = $exists->fetchColumn();

            if ($existingId !== false) {
                $ids[$t['name']] = (int) $existingId;
                continue;
            }

            $stmt->execute([
                'bl' => $t['category'] === 'homecare' ? $homecareId : null,
                'name' => $t['name'], 'category' => $t['category'],
                'subject' => $t['subject'], 'body' => $t['body_html'],
            ]);
            $ids[$t['name']] = (int) $pdo->lastInsertId();
        }

        echo '  seeded ' . count($templates) . " email templates\n";
        $this->templateIds = $ids;
    }

    /** @var array<string,int> */
    private array $templateIds = [];

    private function seedAutomationRules(PDO $pdo): void
    {
        $rules = [
            [
                'name' => 'Welcome Email',
                'trigger_type' => 'lead_created',
                'steps' => [
                    ['step_type' => 'send_email', 'config' => ['template' => 'Welcome — New Lead', 'subject' => 'Welcome to A&B Homecare, {{first_name}}!', 'body_html' => '<p>Hi {{first_name}}, thanks for reaching out — we will be in touch shortly.</p>']],
                ],
            ],
            [
                'name' => 'Follow-up Email',
                'trigger_type' => 'lead_created',
                'steps' => [
                    ['step_type' => 'wait', 'config' => ['delay_hours' => 72]],
                    ['step_type' => 'send_email', 'config' => ['template' => 'Follow-up — Still Interested?', 'subject' => 'Still thinking it over, {{first_name}}?', 'body_html' => '<p>Hi {{first_name}}, just following up on your inquiry.</p>']],
                ],
            ],
            [
                'name' => 'Appointment Reminder',
                'trigger_type' => 'appointment_reminder_check',
                'steps' => [],
                // Intentionally no steps: this workflow row exists only
                // so it's visible/toggleable in the Automation admin
                // list. The actual reminder logic already runs via
                // AppointmentService::sendDueReminders() (Phase 3),
                // which reads appointments.reminder_minutes_before
                // directly — duplicating that as generic workflow
                // steps would just be two implementations of the same
                // thing. See docs/PHASE_4_SUMMARY.md.
            ],
            [
                'name' => 'Birthday Email',
                'trigger_type' => 'customer_birthday',
                'steps' => [
                    ['step_type' => 'send_email', 'config' => ['template' => 'Birthday Greeting', 'subject' => 'Happy Birthday from all of us, {{first_name}}! 🎉', 'body_html' => '<p>Hi {{first_name}}, wishing you a wonderful birthday from the whole A&B team!</p>']],
                ],
            ],
            [
                'name' => 'Re-engagement Campaign',
                'trigger_type' => 'customer_inactive_90d',
                'steps' => [
                    ['step_type' => 'send_email', 'config' => ['template' => 'Re-engagement — We Miss You', 'subject' => "It's been a while, {{first_name}}", 'body_html' => '<p>Hi {{first_name}}, we noticed it\'s been some time — anything we can help with?</p>']],
                ],
            ],
        ];

        $workflowStmt = $pdo->prepare(
            'INSERT INTO automation_workflows (name, trigger_type, is_active, created_at, updated_at)
             VALUES (:name, :trigger, 1, NOW(), NOW())'
        );
        $stepStmt = $pdo->prepare(
            'INSERT INTO automation_steps (workflow_id, step_type, config, sort_order)
             VALUES (:workflow_id, :step_type, :config, :sort_order)'
        );

        $count = 0;
        foreach ($rules as $rule) {
            $exists = $pdo->prepare('SELECT id FROM automation_workflows WHERE name = :name');
            $exists->execute(['name' => $rule['name']]);
            if ($exists->fetchColumn() !== false) {
                continue;
            }

            $workflowStmt->execute(['name' => $rule['name'], 'trigger' => $rule['trigger_type']]);
            $workflowId = (int) $pdo->lastInsertId();

            foreach ($rule['steps'] as $i => $step) {
                $stepStmt->execute([
                    'workflow_id' => $workflowId,
                    'step_type' => $step['step_type'],
                    'config' => json_encode($step['config']),
                    'sort_order' => $i + 1,
                ]);
            }

            $count++;
        }

        echo "  seeded {$count} automation rules\n";
    }

    private function seedAudienceSegments(PDO $pdo): void
    {
        $segments = [
            ['name' => 'High-Priority Homecare Leads', 'description' => 'Homecare leads flagged high or urgent priority.', 'filter' => ['type' => 'leads', 'business_line' => 'homecare', 'priority' => 'high']],
            ['name' => 'Active Customers — Both Brands', 'description' => 'All currently active customers across both business lines.', 'filter' => ['type' => 'customers', 'business_line' => 'both', 'status' => 'active']],
        ];

        $stmt = $pdo->prepare(
            'INSERT INTO audience_segments (name, description, filter_definition, created_at, updated_at)
             VALUES (:name, :description, :filter, NOW(), NOW())'
        );

        $count = 0;
        foreach ($segments as $s) {
            $exists = $pdo->prepare('SELECT id FROM audience_segments WHERE name = :name');
            $exists->execute(['name' => $s['name']]);
            if ($exists->fetchColumn() !== false) {
                continue;
            }

            $stmt->execute(['name' => $s['name'], 'description' => $s['description'], 'filter' => json_encode($s['filter'])]);
            $count++;
        }

        echo "  seeded {$count} audience segments\n";
    }
}
