from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from ..database import get_db
from ..dependencies import get_current_user, require_owner
from ..models import ShiftTemplate, DailyShift, Pump, PumpShiftConfig
from ..schemas import ShiftTemplateCreate, ShiftTemplateUpdate, ShiftTemplateOut

router = APIRouter()


@router.get("/shift-templates", response_model=list[ShiftTemplateOut])
def list_templates(
    include_inactive: bool = False,
    db:    Session = Depends(get_db),
    _=Depends(get_current_user),
):
    q = db.query(ShiftTemplate)
    if not include_inactive:
        q = q.filter(ShiftTemplate.is_active == True)
    return q.order_by(ShiftTemplate.sort_order, ShiftTemplate.id).all()


@router.post("/shift-templates", response_model=ShiftTemplateOut, status_code=201)
def create_template(
    body: ShiftTemplateCreate,
    db:   Session = Depends(get_db),
    user=Depends(require_owner),
):
    code = body.code.upper().strip()
    if db.query(ShiftTemplate).filter(ShiftTemplate.code == code).first():
        raise HTTPException(status_code=409, detail=f"Shift code '{code}' already exists")

    t = ShiftTemplate(
        name=body.name.strip(),
        code=code,
        start_time=body.start_time,
        end_time=body.end_time,
        crosses_midnight=body.crosses_midnight,
        color=body.color,
        is_active=body.is_active,
        sort_order=body.sort_order,
    )
    db.add(t)
    db.flush()

    # Auto-create pump-shift configs for all existing pumps (mirrors create_pump logic)
    if body.is_active:
        pumps = db.query(Pump).all()
        for pump in pumps:
            exists = db.query(PumpShiftConfig).filter(
                PumpShiftConfig.pump_id == pump.id,
                PumpShiftConfig.shift_template_id == t.id,
            ).first()
            if not exists:
                db.add(PumpShiftConfig(pump_id=pump.id, shift_template_id=t.id, sort_order=body.sort_order))

    from .audit import log_audit
    log_audit(db, user.id, 'CREATE', 'shift_templates', t.id,
              f"Created shift template '{code}' ({body.name}) {body.start_time}–{body.end_time}")
    db.commit()
    db.refresh(t)
    return t


@router.put("/shift-templates/{tid}", response_model=ShiftTemplateOut)
def update_template(
    tid:  int,
    body: ShiftTemplateUpdate,
    db:   Session = Depends(get_db),
    user=Depends(require_owner),
):
    t = db.query(ShiftTemplate).filter(ShiftTemplate.id == tid).first()
    if not t:
        raise HTTPException(status_code=404, detail="Shift template not found")

    if body.name             is not None: t.name             = body.name.strip()
    if body.code             is not None:
        new_code = body.code.upper().strip()
        conflict = db.query(ShiftTemplate).filter(
            ShiftTemplate.code == new_code, ShiftTemplate.id != tid
        ).first()
        if conflict:
            raise HTTPException(status_code=409, detail=f"Shift code '{new_code}' already exists")
        t.code = new_code
    if body.start_time       is not None: t.start_time       = body.start_time
    if body.end_time         is not None: t.end_time         = body.end_time
    if body.crosses_midnight is not None: t.crosses_midnight = body.crosses_midnight
    if body.color            is not None: t.color            = body.color
    if body.is_active        is not None: t.is_active        = body.is_active
    if body.sort_order       is not None: t.sort_order       = body.sort_order

    from .audit import log_audit
    log_audit(db, user.id, 'UPDATE', 'shift_templates', t.id,
              f"Updated shift template '{t.code}'")
    db.commit()
    db.refresh(t)
    return t


@router.delete("/shift-templates/{tid}", status_code=204)
def delete_template(
    tid: int,
    db:  Session = Depends(get_db),
    user=Depends(require_owner),
):
    t = db.query(ShiftTemplate).filter(ShiftTemplate.id == tid).first()
    if not t:
        raise HTTPException(status_code=404, detail="Shift template not found")

    has_shifts = db.query(DailyShift).filter(DailyShift.shift_template_id == tid).first()
    if has_shifts:
        raise HTTPException(
            status_code=409,
            detail="Cannot delete a template that has existing shifts. Deactivate it instead."
        )

    from .audit import log_audit
    log_audit(db, user.id, 'DELETE', 'shift_templates', tid, f"Deleted shift template '{t.code}'")
    db.delete(t)
    db.commit()
