from fastapi import APIRouter, HTTPException, Query
from typing import List
from .schemas import VoucherExportRequest, VoucherExportResponse, VoucherDataSummary
from .service import export_vouchers, get_employees_list
import logging

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/payroll/vouchers", tags=["vouchers"])


@router.get("/employees")
def get_employees():
    """従業員リストを取得"""
    try:
        employees = get_employees_list()
        return {
            "total": len(employees),
            "employees": employees,
            "status": "success"
        }
    except Exception as e:
        logger.error(f"従業員リスト取得エラー: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/export")
def export_vouchers_data(request: VoucherExportRequest) -> VoucherExportResponse:
    """账票エクスポート（プレビュー、CSV、PDF）"""
    try:
        result = export_vouchers(request)
        return result
    except ValueError as e:
        logger.error(f"バリデーションエラー: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"エクスポートエラー: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/data/salary")
def get_salary_data(
    employee_id: int = Query(...),
    start_year: int = Query(...),
    start_month: int = Query(...),
    end_year: int = Query(...),
    end_month: int = Query(...)
):
    """単一従業員の給与データ取得"""
    try:
        from .service import get_salary_data_for_period
        data = get_salary_data_for_period(
            employee_id,
            start_year,
            start_month,
            end_year,
            end_month
        )
        return {
            "status": "success",
            "data": data
        }
    except Exception as e:
        logger.error(f"給与データ取得エラー: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/data/bonus")
def get_bonus_data(
    employee_id: int = Query(...),
    start_year: int = Query(...),
    start_month: int = Query(...),
    end_year: int = Query(...),
    end_month: int = Query(...)
):
    """単一従業員の賞与データ取得"""
    try:
        from .service import get_bonus_data_for_period
        data = get_bonus_data_for_period(
            employee_id,
            start_year,
            start_month,
            end_year,
            end_month
        )
        return {
            "status": "success",
            "data": data
        }
    except Exception as e:
        logger.error(f"賞与データ取得エラー: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))
