<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Database;

final class MarketingConnection extends BaseModel
{
    protected static string $table = 'marketing_connections';
    protected static bool $softDelete = false;

    public static function allForTenant(): array
    {
        $rows = static::db()->fetchAll(
            'SELECT * FROM marketing_connections WHERE tenant_id = :tid',
            ['tid' => static::tenantId()]
        );
        $map = [];
        foreach ($rows as $r) {
            $map[$r['provider']] = $r;
        }
        return $map;
    }

    public static function upsert(string $provider, string $status): void
    {
        $existing = static::db()->fetch(
            'SELECT id FROM marketing_connections WHERE tenant_id = :tid AND provider = :p',
            ['tid' => static::tenantId(), 'p' => $provider]
        );
        if ($existing) {
            static::db()->query(
                "UPDATE marketing_connections SET status = :st, connected_at = IF(:st2 = 'connected', NOW(), NULL) WHERE id = :id",
                ['st' => $status, 'st2' => $status, 'id' => $existing['id']]
            );
            return;
        }
        static::create([
            'provider' => $provider,
            'status' => $status,
            'connected_at' => $status === 'connected' ? date('Y-m-d H:i:s') : null,
        ]);
    }

    public static function activeProvider(): ?string
    {
        $row = static::db()->fetch(
            "SELECT provider FROM marketing_connections WHERE tenant_id = :tid AND status = 'connected' ORDER BY connected_at DESC LIMIT 1",
            ['tid' => static::tenantId()]
        );
        return $row['provider'] ?? null;
    }
}
