"""企业实体 API"""
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from typing import List, Optional
from pydantic import BaseModel

from app.database import get_db
from app.auth_middleware import require_auth
from app.models import Entity

router = APIRouter(prefix="/api/cma/entities", tags=["企业实体"],
    dependencies=[Depends(require_auth)],
)


class EntityCreate(BaseModel):
    name: str
    short_name: Optional[str] = None
    industry: Optional[str] = None
    status: Optional[str] = "active"


class EntityUpdate(BaseModel):
    name: Optional[str] = None
    short_name: Optional[str] = None
    industry: Optional[str] = None
    status: Optional[str] = None


@router.get("")
def list_entities(db: Session = Depends(get_db)):
    """获取企业列表"""
    entities = db.query(Entity).filter(Entity.status == "active").order_by(Entity.id).all()
    return {
        "data": [
            {
                "id": e.id,
                "name": e.name,
                "short_name": e.short_name,
                "industry": e.industry,
            }
            for e in entities
        ]
    }


@router.post("")
def create_entity(data: EntityCreate, db: Session = Depends(get_db)):
    """创建企业"""
    entity = Entity(
        name=data.name,
        short_name=data.short_name,
        industry=data.industry,
        status=data.status or "active",
    )
    db.add(entity)
    db.commit()
    db.refresh(entity)
    return {
        "id": entity.id,
        "name": entity.name,
        "short_name": entity.short_name,
        "industry": entity.industry,
        "message": "企业创建成功",
    }


@router.put("/{entity_id}")
def update_entity(entity_id: int, data: EntityUpdate, db: Session = Depends(get_db)):
    """更新企业信息"""
    entity = db.query(Entity).filter(Entity.id == entity_id).first()
    if not entity:
        from fastapi.responses import JSONResponse
        return JSONResponse(status_code=404, content={"detail": "企业不存在"})

    if data.name is not None:
        entity.name = data.name
    if data.short_name is not None:
        entity.short_name = data.short_name
    if data.industry is not None:
        entity.industry = data.industry
    if data.status is not None:
        entity.status = data.status

    db.commit()
    db.refresh(entity)
    return {
        "id": entity.id,
        "name": entity.name,
        "short_name": entity.short_name,
        "industry": entity.industry,
        "message": "企业更新成功",
    }
