"""Import/export routes — CSV import, dry-run preview, CSV/XLSX export.""" from __future__ import annotations import uuid from typing import Any from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, Query, Response, status from sqlalchemy.ext.asyncio import AsyncSession from app.core.auth import check_permission from app.core.db import get_db from app.deps import get_current_user from app.services import import_export_service from app.services import company_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(get_current_user), ): """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"]) role = current_user.get("role", "viewer") if not check_permission(role, "companies", "create"): raise HTTPException(403, detail={"detail": "Insufficient permissions", "code": "forbidden"}) 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(get_current_user), ): """Preview CSV import (dry-run — no DB changes).""" tenant_id = uuid.UUID(current_user["tenant_id"]) user_id = uuid.UUID(current_user["user_id"]) role = current_user.get("role", "viewer") if not check_permission(role, "companies", "read"): raise HTTPException(403, detail={"detail": "Insufficient permissions", "code": "forbidden"}) 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