"""Import/export routes — CSV import, dry-run preview, CSV/XLSX export.""" from __future__ import annotations import uuid from fastapi import ( APIRouter, Depends, File, Form, HTTPException, UploadFile, ) from sqlalchemy.ext.asyncio import AsyncSession from app.core.db import get_db from app.deps import require_permission from app.services import import_export_service router = APIRouter(prefix="/api/v1", tags=["import_export"]) @router.post("/import") async def import_csv( file: UploadFile = File(...), entity_type: str = Form("companies"), db: AsyncSession = Depends(get_db), current_user: dict = Depends(require_permission("import_export:write")), ): """Import companies or contacts from CSV file. entity_type: 'companies' or 'contacts'. """ tenant_id = uuid.UUID(current_user["tenant_id"]) user_id = uuid.UUID(current_user["user_id"]) content = await file.read() csv_content = content.decode("utf-8") result = await import_export_service.import_csv( db, tenant_id, user_id, csv_content, entity_type=entity_type, dry_run=False, ) return result @router.post("/import/preview") async def import_csv_preview( file: UploadFile = File(...), entity_type: str = Form("companies"), db: AsyncSession = Depends(get_db), current_user: dict = Depends(require_permission("import_export:read")), ): """Preview CSV import (dry-run — no DB changes).""" tenant_id = uuid.UUID(current_user["tenant_id"]) user_id = uuid.UUID(current_user["user_id"]) content = await file.read() csv_content = content.decode("utf-8") result = await import_export_service.import_csv( db, tenant_id, user_id, csv_content, entity_type=entity_type, dry_run=True, ) return result