from fastapi import APIRouter, Depends, HTTPException
from typing import List
from datetime import datetime
from psycopg import AsyncConnection

from app.infra.db.timescaledb.repositories.scada import ScadaRepository
from .dependencies import get_timescale_connection

router = APIRouter()


@router.post("/scada/batch", status_code=201)
async def insert_scada_data(
    data: List[dict], conn: AsyncConnection = Depends(get_timescale_connection)
):
    await ScadaRepository.insert_scada_batch(conn, data)
    return {"message": f"Inserted {len(data)} records"}


@router.get("/scada/by-ids-time-range")
async def get_scada_by_ids_time_range(
    start_time: datetime,
    end_time: datetime,
    device_ids: str,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    device_ids_list = (
        [id.strip() for id in device_ids.split(",") if id.strip()] if device_ids else []
    )
    return await ScadaRepository.get_scada_by_ids_time_range(
        conn, device_ids_list, start_time, end_time
    )


@router.get("/scada/by-ids-field-time-range")
async def get_scada_field_by_ids_time_range(
    start_time: datetime,
    end_time: datetime,
    field: str,
    device_ids: str,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    try:
        device_ids_list = (
            [id.strip() for id in device_ids.split(",") if id.strip()]
            if device_ids
            else []
        )
        return await ScadaRepository.get_scada_field_by_id_time_range(
            conn, device_ids_list, start_time, end_time, field
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.patch("/scada/{device_id}/field")
async def update_scada_field(
    device_id: str,
    time: datetime,
    field: str,
    value: float,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    try:
        await ScadaRepository.update_scada_field(conn, time, device_id, field, value)
        return {"message": "Updated successfully"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.delete("/scada/by-id-time-range")
async def delete_scada_data(
    device_id: str,
    start_time: datetime,
    end_time: datetime,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    await ScadaRepository.delete_scada_by_id_time_range(
        conn, device_id, start_time, end_time
    )
    return {"message": "Deleted successfully"}
