<?php
declare(strict_types=1);

require_once __DIR__ . '/../db/config.php';

function ensure_schema(): void {
    $pdo = db();
    $sqlFile = __DIR__ . '/../db/migrations/001_sms_chat.sql';
    if (!file_exists($sqlFile)) {
        throw new RuntimeException('Schema file missing.');
    }

    $sql = file_get_contents($sqlFile);
    $statements = array_filter(array_map('trim', preg_split('/;\s*\n/', (string)$sql)));
    foreach ($statements as $statement) {
        if ($statement !== '') {
            $pdo->exec($statement);
        }
    }

    $stmt = $pdo->prepare("INSERT INTO settings (name, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = value");
    $stmt->execute(['sms_unit_price', '0.05']);

    $count = (int)$pdo->query("SELECT COUNT(*) FROM conversations")->fetchColumn();
    if ($count === 0) {
        $convStmt = $pdo->prepare("INSERT INTO conversations (contact_name, phone, channel, created_at) VALUES (?, ?, ?, NOW())");
        $msgStmt = $pdo->prepare("INSERT INTO messages (conversation_id, direction, body, status, created_at) VALUES (?, ?, ?, ?, NOW())");
        $billStmt = $pdo->prepare("INSERT INTO billing_events (message_id, units, unit_price, total_cost, created_at) VALUES (?, ?, ?, ?, NOW())");

        $convStmt->execute(['Horizon Logistics', '+1 415 555 0118', 'twilio']);
        $convA = (int)$pdo->lastInsertId();
        $msgStmt->execute([$convA, 'outbound', 'Hello! Your shipment is scheduled for pickup today at 3 PM.', 'sent']);
        $msgA = (int)$pdo->lastInsertId();
        $billStmt->execute([$msgA, 1, 0.05, 0.05]);
        $msgStmt->execute([$convA, 'inbound', 'Great, please confirm the driver ID when ready.', 'received']);

        $convStmt->execute(['Nova Care Clinic', '+1 212 555 0199', 'aliyun']);
        $convB = (int)$pdo->lastInsertId();
        $msgStmt->execute([$convB, 'outbound', 'Reminder: your appointment is tomorrow at 9:00 AM.', 'sent']);
        $msgB = (int)$pdo->lastInsertId();
        $billStmt->execute([$msgB, 1, 0.05, 0.05]);
        $msgStmt->execute([$convB, 'inbound', 'Confirmed. Thank you!', 'received']);
    }
}
