from fastapi import APIRouter, Depends, HTTPException from sqlalchemy import func, text from sqlalchemy.orm import Session from typing import List from ..database import get_db from ..models import Account from ..schemas import AccountCreate, AccountUpdate, AccountOut, ConnectionTestResult, TestPayload router = APIRouter(prefix="/accounts", tags=["accounts"]) @router.get("/", response_model=List[AccountOut]) def list_accounts(db: Session = Depends(get_db)): return db.query(Account).all() @router.post("/", response_model=AccountOut, status_code=201) def create_account(payload: AccountCreate, db: Session = Depends(get_db)): if db.query(Account).filter(Account.email == payload.email).first(): raise HTTPException(status_code=409, detail="Account with this email already exists") obj = Account(**payload.model_dump()) db.add(obj) db.commit() db.refresh(obj) return obj @router.get("/{account_id}", response_model=AccountOut) def get_account(account_id: int, db: Session = Depends(get_db)): obj = db.get(Account, account_id) if not obj: raise HTTPException(status_code=404, detail="Account not found") return obj @router.put("/{account_id}", response_model=AccountOut) @router.patch("/{account_id}", response_model=AccountOut) def update_account(account_id: int, payload: AccountUpdate, db: Session = Depends(get_db)): obj = db.get(Account, account_id) if not obj: raise HTTPException(status_code=404, detail="Account not found") for field, value in payload.model_dump(exclude_unset=True).items(): setattr(obj, field, value) db.commit() db.refresh(obj) return obj @router.delete("/{account_id}", status_code=204) def delete_account(account_id: int, db: Session = Depends(get_db)): obj = db.get(Account, account_id) if not obj: raise HTTPException(status_code=404, detail="Account not found") db.delete(obj) db.commit() @router.post("/{account_id}/test", response_model=ConnectionTestResult) def test_account(account_id: int, db: Session = Depends(get_db)): obj = db.get(Account, account_id) if not obj: raise HTTPException(status_code=404, detail="Account not found") payload = TestPayload( imap_host=obj.imap_host, imap_port=obj.imap_port, imap_user=obj.imap_user, imap_password=obj.imap_password, smtp_host=obj.smtp_host, smtp_port=obj.smtp_port, smtp_user=obj.smtp_user, smtp_password=obj.smtp_password, bizdocs_api_key=obj.bizdocs_api_key, bizdocs_entity_id=obj.bizdocs_entity_id, ) from .connection import _run_test return _run_test(payload)