"Financial Information router"

from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from sqlalchemy.exc import SQLAlchemyError
from http import HTTPStatus
from typing import List
from schemas.financial_information import (
    FinancialInformationPageResponse,
    FinancialInformationPageCreate,
    FinancialInformationTemplateResponse,
    FinancialInformationTableResponse,
    FinancialInformationTableCreate,
    FinancialInformationPageUpdate,
)
from services.financial_info.page_service import FinancialInformationPageService
from services.financial_info.templates import FinancialInformationTemplateService
from services.financial_info.table_service import FinancialInformationTableService
from utils.logger import ServiceLogger
from utils.mysql_db import MySQLDB

service_logger = ServiceLogger()
logger = service_logger.get_logger("WARNING")


financial_info = APIRouter(
    prefix="/financial_info",
    tags=["financial_info"],
    responses={404: {"description": "Not found"}},
    dependencies=[],
)

mysql_db = MySQLDB()


@financial_info.post("/pages", response_model=FinancialInformationPageResponse)
async def create_page(
    page_data: FinancialInformationPageCreate,
    request: Request,
):
    """
    Create a new financial information page.
    """
    try:
        current_user = request.state.current_user

        created_page = await FinancialInformationPageService.insert_new_record(
            mysql_db, current_user=current_user, **page_data.model_dump()
        )
        return created_page
    except SQLAlchemyError as e:
        logger.error("Error creating page: %s", e)
        raise HTTPException(
            status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Internal Server Error"
        ) from e


@financial_info.get("/pages", response_model=List[FinancialInformationPageResponse])
async def get_pages():
    """
    Get all financial information pages.
    """
    try:
        response = await FinancialInformationPageService.get_all_records(mysql_db)
        return response
    except SQLAlchemyError as e:
        logger.error("Error getting pages: %s", e)
        raise HTTPException(
            status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Internal Server Error"
        ) from e


@financial_info.get(
    "/pages/{project_id}", response_model=List[FinancialInformationPageResponse]
)
async def get_pages_for_project(project_id: str):
    """
    Get all financial information pages for a project.
    """
    try:
        response = await FinancialInformationPageService.get_all_records_for_project(
            mysql_db, project_id
        )
        return response
    except SQLAlchemyError as e:
        logger.error("Error getting pages: %s", e)
        raise HTTPException(
            status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Internal Server Error"
        ) from e


@financial_info.get("/page/{page_id}", response_model=FinancialInformationPageResponse)
async def get_page(page_id: int):
    """
    Get a financial information page by id.
    """
    try:
        page = await FinancialInformationPageService.get_record_by_id(mysql_db, page_id)
        if page:
            return page[0]
        return None
    except SQLAlchemyError as e:
        logger.error("Error getting page: %s", e)
        raise HTTPException(
            status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Internal Server Error"
        ) from e


@financial_info.delete("/page/{page_id}", status_code=HTTPStatus.NO_CONTENT)
async def delete_page(page_id: int, request: Request):
    """
    Mark a financial information page as inactive by id.
    """
    try:
        current_user = request.state.current_user
        await FinancialInformationPageService.update_record_by_id(
            mysql_db, page_id, is_active=False, current_user=current_user
        )

        return JSONResponse(
            status_code=HTTPStatus.OK,
            content={"message": "Page marked as inactive successfully"},
        )
    except SQLAlchemyError as e:
        logger.error("Error marking page as inactive: %s", e)
        raise HTTPException(
            status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Internal Server Error"
        ) from e


@financial_info.get(
    "/templates", response_model=List[FinancialInformationTemplateResponse]
)
async def get_templates():
    """
    Get all financial information templates.
    """
    try:
        response = await FinancialInformationTemplateService.get_all_records(mysql_db)
        return response
    except SQLAlchemyError as e:
        logger.error("Error getting pages: %s", e)
        raise HTTPException(
            status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Internal Server Error"
        ) from e


@financial_info.post(
    "/save/{project_id}/{page_id}", response_model=FinancialInformationTableResponse
)
async def save_page(page_data: FinancialInformationTableCreate, request: Request):
    """
    Save a financial information page by id.
    """
    try:
        current_user = request.state.current_user
        saved_page = await FinancialInformationTableService.save_record(
            mysql_db, current_user=current_user, **page_data.model_dump()
        )
        return saved_page
    except SQLAlchemyError as e:
        logger.error("Error saving page: %s", e)
        raise HTTPException(
            status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Internal Server Error"
        ) from e


@financial_info.get(
    "/table/{project_id}/{page_id}",
    response_model=FinancialInformationTableResponse | None,
)
async def get_table(project_id: str, page_id: int):
    """
    Get a financial information table by id.
    """
    try:
        response = await FinancialInformationTableService.get_record_by_id(
            mysql_db, page_id, project_id
        )
        return response
    except SQLAlchemyError as e:
        logger.error("Error getting table: %s", e)
        raise HTTPException(
            status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Internal Server Error"
        ) from e


@financial_info.put("/pages/{page_id}")
async def update_page(
    page_id: int, page_data: FinancialInformationPageUpdate, request: Request
):
    """
    Update a financial information page by id.
    """
    try:
        current_user = request.state.current_user
        updated_page = await FinancialInformationPageService.update_record_by_id(
            mysql_db, page_id, current_user=current_user, **page_data.model_dump()
        )
        return updated_page
    except SQLAlchemyError as e:
        logger.error("Error updating page: %s", e)
        raise HTTPException(
            status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Internal Server Error"
        ) from e
