<?php
declare(strict_types=1);

namespace App\Models;

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

    public static function forUser(int $userId): array
    {
        return static::db()->fetchAll(
            'SELECT * FROM integrations WHERE tenant_id = :tid AND user_id = :uid',
            ['tid' => static::tenantId(), 'uid' => $userId]
        );
    }

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

    public static function isConnected(int $userId, string $provider, string $kind): bool
    {
        $row = static::db()->fetch(
            "SELECT id FROM integrations WHERE tenant_id = :tid AND user_id = :uid AND provider = :p AND kind = :k AND status = 'connected'",
            ['tid' => static::tenantId(), 'uid' => $userId, 'p' => $provider, 'k' => $kind]
        );
        return $row !== null;
    }
}
