
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
from {{ base_package }}.shared.database import get_db
# 引用 Shared Models (位于当前切片的父目录 model.py)
from ..model import {{ table.class_name }}

from typing import List

router = APIRouter()

# --- 1. 数据模型 (Schemas) ---
class RequestDTO(BaseModel):
    {% if op == 'create' or op == 'update' %}
    {% for col in table.columns if not col.is_pk -%}
    {{ col.name }}: {{ col.python_type }}{% if col.nullable %} = None{% endif %}
    {% endfor %}
    {% else %}
    # 对于 GET/DELETE 请求，通常 ID 在路径中，这里仅作为占位符
    pass
    {% endif %}

class ResponseDTO(BaseModel):
    {% for col in table.columns -%}
    {{ col.name }}: {{ col.python_type }}{% if col.nullable %} = None{% endif %}
    {% endfor %}
    
    class Config:
        from_attributes = True

# --- 2. 业务逻辑 (Logic) ---
def {{ op }}_logic(req: RequestDTO, db: Session, id: int = None) -> {% if op == 'get_list' %}List[ResponseDTO]{% else %}ResponseDTO{% endif %}:
    {% if op == 'create' %}
    db_obj = {{ table.class_name }}(**req.model_dump())
    db.add(db_obj)
    db.commit()
    db.refresh(db_obj)
    return db_obj
    {% elif op == 'get_by_id' %}
    item = db.query({{ table.class_name }}).filter({{ table.class_name }}.id == id).first()
    if not item: raise HTTPException(404, "未找到")
    return item
    {% elif op == 'delete' %}
    item = db.query({{ table.class_name }}).filter({{ table.class_name }}.id == id).first()
    if not item: raise HTTPException(404, "未找到")
    db.delete(item)
    db.commit()
    return item # 或简单的成功消息
    {% elif op == 'update' %}
    item = db.query({{ table.class_name }}).filter({{ table.class_name }}.id == id).first()
    if not item: raise HTTPException(404, "未找到")
    for key, value in req.model_dump(exclude_unset=True).items():
        setattr(item, key, value)
    db.commit()
    db.refresh(item)
    return item
    {% elif op == 'get_list' %}
    return db.query({{ table.class_name }}).all()
    {% else %}
    return ResponseDTO()
    {% endif %}

# --- 3. 路由接口 (Endpoint) ---
{% if op == 'get_by_id' or op == 'delete' or op == 'update' %}
@router.{{ method | lower }}("/{id}", response_model=ResponseDTO)
async def endpoint(id: int, {% if op != 'delete' and op != 'get_by_id' %}req: RequestDTO,{% endif %} db: Session = Depends(get_db)):
    return {{ op }}_logic({% if op != 'delete' and op != 'get_by_id' %}req,{% else %}None,{% endif %} db, id)
{% elif op == 'get_list' %}
@router.get("/", response_model=List[ResponseDTO])
async def endpoint(db: Session = Depends(get_db)):
    return {{ op }}_logic(None, db)
{% else %}
@router.{{ method | lower }}("/", response_model=ResponseDTO)
async def endpoint(req: RequestDTO, db: Session = Depends(get_db)):
    return {{ op }}_logic(req, db)
{% endif %}
