"""Shared fixtures for MySQL adapter tests."""

from __future__ import annotations

import os

import mysql.connector
import pytest

from db_test_helpers.mysql._adapter import _quote_identifier


@pytest.fixture
def conn():
    connection = mysql.connector.connect(
        host=os.environ.get("MYSQL_HOST", "localhost"),
        port=int(os.environ.get("MYSQL_PORT", "3306")),
        user=os.environ.get("MYSQL_USER", "test"),
        password=os.environ.get("MYSQL_PASSWORD", "test"),
        database=os.environ.get("MYSQL_DATABASE", "testdb"),
    )
    yield connection
    connection.close()


_TABLES = ["users", "posts"]


@pytest.fixture(autouse=True)
def _setup_tables(request):
    if "conn" not in request.fixturenames:
        yield
        return
    conn = request.getfixturevalue("conn")
    cursor = conn.cursor()
    try:
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(255),
                age INT,
                email VARCHAR(255),
                score DECIMAL(10, 2),
                created_at DATETIME,
                birth_date DATE,
                login_time TIME,
                bio BLOB
            )
        """)
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS posts (
                id INT AUTO_INCREMENT PRIMARY KEY,
                title VARCHAR(255),
                body TEXT,
                user_name VARCHAR(255)
            )
        """)
        conn.commit()
    finally:
        cursor.close()

    yield

    cursor = conn.cursor()
    try:
        cursor.execute("SET FOREIGN_KEY_CHECKS = 0")
        for table in _TABLES:
            cursor.execute(f"TRUNCATE TABLE {_quote_identifier(table)}")
        cursor.execute("SET FOREIGN_KEY_CHECKS = 1")
        conn.commit()
    finally:
        cursor.close()
