<?php
require_once __DIR__ . '/../Core.php';

class ConnectorConfig extends Model
{
    public function all(): array
    {
        $stmt = $this->db->query('SELECT cc.*, u.name AS created_by_name FROM connector_configs cc LEFT JOIN users u ON u.id = cc.created_by ORDER BY cc.is_active DESC, cc.name ASC');
        return $stmt->fetchAll();
    }

    public function active(): array
    {
        $stmt = $this->db->query('SELECT * FROM connector_configs WHERE is_active = 1 ORDER BY connector_key ASC, name ASC');
        return $stmt->fetchAll();
    }

    public function save(array $data): int
    {
        $id = (int)($data['id'] ?? 0);
        $connectorKey = trim((string)($data['connector_key'] ?? 'custom')) ?: 'custom';
        $name = trim((string)($data['name'] ?? 'Connector')) ?: 'Connector';
        $baseUrl = trim((string)($data['base_url'] ?? ''));
        $authType = trim((string)($data['auth_type'] ?? 'bearer')) ?: 'bearer';
        $accessToken = trim((string)($data['access_token'] ?? ''));
        $refreshToken = trim((string)($data['refresh_token'] ?? ''));
        $configJson = is_array($data['config_json'] ?? null) ? json_encode($data['config_json'], JSON_UNESCAPED_SLASHES) : (trim((string)($data['config_json'] ?? '')) ?: '{}');
        $isActive = !empty($data['is_active']) ? 1 : 0;
        if ($id > 0) {
            $stmt = $this->db->prepare('UPDATE connector_configs SET connector_key = ?, name = ?, base_url = ?, auth_type = ?, access_token = ?, refresh_token = ?, config_json = ?, is_active = ?, updated_at = NOW() WHERE id = ?');
            $stmt->execute([$connectorKey, $name, $baseUrl, $authType, $accessToken, $refreshToken, $configJson, $isActive, $id]);
            return $id;
        }
        $stmt = $this->db->prepare('INSERT INTO connector_configs (connector_key, name, base_url, auth_type, access_token, refresh_token, config_json, is_active, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([$connectorKey, $name, $baseUrl, $authType, $accessToken, $refreshToken, $configJson, $isActive, (int)(current_user()['id'] ?? 0) ?: null]);
        return (int)$this->db->lastInsertId();
    }

    public function delete(int $id): void
    {
        $stmt = $this->db->prepare('DELETE FROM connector_configs WHERE id = ?');
        $stmt->execute([$id]);
    }
}
