<?php

declare(strict_types=1);

namespace Database\Seeders;

use PDO;

/**
 * AiIntegrationSeeder
 *
 * Adds the Phase 5 integration catalog entries not already seeded by
 * Phase 1's WorkspaceSeeder (which covered twilio and google_calendar
 * as part of the original 6). Also seeds one starter AI prompt per
 * feature and a handful of starter Knowledge Base articles so the
 * Chatbot/AI Assistant have something real to search on day one.
 */
final class AiIntegrationSeeder implements SeederInterface
{
    public function run(PDO $pdo): void
    {
        $integrations = [
            ['name' => 'OpenAI', 'slug' => 'openai'],
            ['name' => 'ElevenLabs', 'slug' => 'elevenlabs'],
            ['name' => 'WhatsApp Business API', 'slug' => 'whatsapp'],
            ['name' => 'Google OAuth (Sign-In)', 'slug' => 'google_oauth'],
            ['name' => 'Facebook Lead Ads', 'slug' => 'facebook'],
            ['name' => 'Instagram Lead Ads', 'slug' => 'instagram'],
            ['name' => 'TikTok Lead Generation', 'slug' => 'tiktok'],
            ['name' => 'Meta Pixel', 'slug' => 'meta_pixel'],
            ['name' => 'Google Analytics', 'slug' => 'google_analytics'],
        ];

        $stmt = $pdo->prepare(
            'INSERT IGNORE INTO integrations (name, slug, status, created_at, updated_at) VALUES (:name, :slug, "not_connected", NOW(), NOW())'
        );

        $count = 0;
        foreach ($integrations as $i) {
            $exists = $pdo->prepare('SELECT id FROM integrations WHERE slug = :slug');
            $exists->execute(['slug' => $i['slug']]);
            if ($exists->fetchColumn() !== false) {
                continue;
            }
            $stmt->execute($i);
            $count++;
        }

        echo "  seeded {$count} integrations\n";

        $prompts = [
            [
                'feature' => 'ai_assistant', 'business_line_id' => null, 'name' => 'Default Assistant Prompt',
                'system_prompt' => 'You are the internal AI Assistant for A&B Hub. You help staff at A&B Homecare Services and A&B Cleaner Janitorial Services search records, book appointments, generate reports, and answer questions. Be concise and always confirm details before taking an action like booking an appointment.',
            ],
            [
                'feature' => 'chatbot', 'business_line_id' => null, 'name' => 'Default Chatbot Prompt',
                'system_prompt' => 'You are a friendly website assistant for A&B Homecare Services and A&B Cleaner Janitorial Services. Help visitors with questions, capture their contact information if they are interested in services, and offer to book an appointment. If you are unsure, offer to connect them with a team member.',
            ],
            [
                'feature' => 'voice_agent', 'business_line_id' => null, 'name' => 'Default Voice Agent Prompt',
                'system_prompt' => 'You are a phone assistant for A&B Homecare Services and A&B Cleaner Janitorial Services. Keep responses brief and natural for speech. Qualify the caller\'s needs, offer to book an appointment, and escalate to a human if asked.',
            ],
        ];

        $promptStmt = $pdo->prepare(
            'INSERT INTO ai_prompts (feature, business_line_id, name, system_prompt, is_active, created_at, updated_at)
             VALUES (:feature, :bl, :name, :prompt, 1, NOW(), NOW())'
        );

        $promptCount = 0;
        foreach ($prompts as $p) {
            $exists = $pdo->prepare('SELECT id FROM ai_prompts WHERE name = :name');
            $exists->execute(['name' => $p['name']]);
            if ($exists->fetchColumn() !== false) {
                continue;
            }
            $promptStmt->execute(['feature' => $p['feature'], 'bl' => $p['business_line_id'], 'name' => $p['name'], 'prompt' => $p['system_prompt']]);
            $promptCount++;
        }

        echo "  seeded {$promptCount} AI prompts\n";

        $articles = [
            ['category' => 'general', 'question' => 'What areas do you service?', 'answer' => 'We proudly service the greater San Diego area for both homecare and janitorial services.'],
            ['category' => 'billing', 'question' => 'What payment methods do you accept?', 'answer' => 'We accept all major credit cards, e-transfer, and pre-authorized debit for recurring plans.'],
            ['category' => 'scheduling', 'question' => 'How do I reschedule an appointment?', 'answer' => 'You can call us, message our chatbot, or use your account portal to reschedule anytime with at least 24 hours notice.'],
            ['category' => 'general', 'question' => 'Are your caregivers background checked?', 'answer' => 'Yes — every caregiver completes a full background check, reference verification, and in-person interview before joining our team.'],
        ];

        $kbStmt = $pdo->prepare(
            'INSERT INTO knowledge_base_articles (category, question, answer, is_active, created_at, updated_at)
             VALUES (:category, :question, :answer, 1, NOW(), NOW())'
        );

        $kbCount = 0;
        foreach ($articles as $a) {
            $exists = $pdo->prepare('SELECT id FROM knowledge_base_articles WHERE question = :question');
            $exists->execute(['question' => $a['question']]);
            if ($exists->fetchColumn() !== false) {
                continue;
            }
            $kbStmt->execute($a);
            $kbCount++;
        }

        echo "  seeded {$kbCount} knowledge base articles\n";
    }
}
