"""Opportunity CRM APIs — Phase 6.2."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Body, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_pagination, require_tenant
from app.core.security import get_current_user
from app.repositories.sales_engine import SalesStageHistoryRepository
from app.schemas.foundation import (
    OpportunityCreate,
    OpportunityLoseRequest,
    OpportunityRead,
    OpportunityStageChangeRequest,
    OpportunityUpdate,
    OpportunityWinRequest,
    StageHistoryRead,
)
from app.services.opportunity_service import OpportunityService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=OpportunityRead, status_code=status.HTTP_201_CREATED)
async def create_opportunity(
    body: OpportunityCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await OpportunityService(db).create(tenant_id, body, actor=user)


@router.get("", response_model=list[OpportunityRead])
async def list_opportunities(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(get_current_user),
):
    return await OpportunityService(db).list(
        tenant_id, offset=pagination.offset, limit=pagination.page_size
    )


@router.get("/{opportunity_id}", response_model=OpportunityRead)
async def get_opportunity(
    opportunity_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(get_current_user),
):
    return await OpportunityService(db).get(tenant_id, opportunity_id)


@router.patch("/{opportunity_id}", response_model=OpportunityRead)
async def update_opportunity(
    opportunity_id: UUID,
    body: OpportunityUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await OpportunityService(db).update(
        tenant_id, opportunity_id, body, actor=user
    )


@router.post("/{opportunity_id}/stage", response_model=OpportunityRead)
async def change_opportunity_stage(
    opportunity_id: UUID,
    body: OpportunityStageChangeRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await OpportunityService(db).change_stage(
        tenant_id, opportunity_id, body, actor=user
    )


@router.get(
    "/{opportunity_id}/stage-history", response_model=list[StageHistoryRead]
)
async def list_stage_history(
    opportunity_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(get_current_user),
):
    await OpportunityService(db).get(tenant_id, opportunity_id)
    return await SalesStageHistoryRepository(db).list_by_opportunity(
        tenant_id, opportunity_id
    )


@router.post("/{opportunity_id}/win", response_model=OpportunityRead)
async def win_opportunity(
    opportunity_id: UUID,
    body: OpportunityWinRequest | None = Body(default=None),
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await OpportunityService(db).mark_won(
        tenant_id, opportunity_id, body, actor=user
    )


@router.post("/{opportunity_id}/lose", response_model=OpportunityRead)
async def lose_opportunity(
    opportunity_id: UUID,
    body: OpportunityLoseRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await OpportunityService(db).mark_lost(
        tenant_id, opportunity_id, body, actor=user
    )
