import os
import tempfile

import pytest


@pytest.fixture()
def app():
    """Create app with a temporary file-based SQLite DB, removed after the test."""
    db_fd, db_path = tempfile.mkstemp(suffix=".db")
    os.close(db_fd)

    class TestConfig:
        SQLALCHEMY_DATABASE_URI = f"sqlite:///{db_path}"
        SECRET_KEY = "test-secret"
        SQLALCHEMY_TRACK_MODIFICATIONS = False
        TESTING = True
        WTF_CSRF_ENABLED = False      # disable CSRF validation in tests
        HOMEASSISTANT_URL = None      # prevent HA poller from starting in tests
        HOMEASSISTANT_API_KEY = None

    from app import create_app
    flask_app = create_app(TestConfig)

    yield flask_app

    os.unlink(db_path)


@pytest.fixture()
def client(app):
    return app.test_client()


@pytest.fixture()
def seeded_client(app):
    """Test client pre-loaded with 2 devices and 3 batteries (2 available, 1 retired).

    Batteries:
      id=1  BrandX 001  (BrandX, available)
      id=2  BrandY 001  (BrandY, available)
      id=3  BrandX 002  (BrandX, retired)
    """
    with app.test_client() as c:
        c.post("/device/add", data={"name": "Device A", "battery_slots": "2", "battery_size": "AA"})
        c.post("/device/add", data={"name": "Device B", "battery_slots": "1", "battery_size": "AA"})
        c.post("/battery/add", data={"brand": "BrandX", "count": "1"})  # id=1
        c.post("/battery/add", data={"brand": "BrandY", "count": "1"})  # id=2
        c.post("/battery/add", data={"brand": "BrandX", "count": "1"})  # id=3
        c.post("/battery/3/retire")
        yield c
