using System.Data.Common;
using Microsoft.Data.Sqlite;
using MySqlConnector;

namespace Eis.Infrastructure.Data;

public sealed class RelationalConnectionFactory(DatabaseOptions options) : IRelationalConnectionFactory
{
    public async ValueTask<DbConnection> OpenAsync(CancellationToken cancellationToken)
    {
        if (options.Client == "sqlite" && options.SqlitePath is { } sqlitePath)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(sqlitePath)
                                      ?? throw new InvalidOperationException("SQLite 数据库路径无效"));
        }
        DbConnection connection = options.Client switch
        {
            "sqlite" => new SqliteConnection(new SqliteConnectionStringBuilder
            {
                DataSource = options.SqlitePath,
                Mode = SqliteOpenMode.ReadWriteCreate,
                Cache = SqliteCacheMode.Shared,
                ForeignKeys = true,
                DefaultTimeout = 5,
                Pooling = false
            }.ConnectionString),
            "mysql" => new MySqlConnection(options.MySqlConnectionString),
            _ => throw new InvalidOperationException($"不支持的数据库类型：{options.Client}")
        };

        try
        {
            await connection.OpenAsync(cancellationToken);
            return connection;
        }
        catch
        {
            await connection.DisposeAsync();
            throw;
        }
    }
}
