File size: 5,218 Bytes
b613c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""Chat API Routes — Mediated Messaging between Recruiters and Talents.

Endpoints:
  POST   /v1/chat/send       — Recruiter sends message to talent
  POST   /v1/chat/reply      — Talent replies to conversation
  POST   /v1/chat/unlock     — Unlock identity (5 coins)
  GET    /v1/chat/conversations    — List conversations (recruiter view)
  GET    /v1/chat/talent/conversations  — List conversations (talent view)
  GET    /v1/chat/history     — Get message history

All endpoints use crash-proof AI mediation via Gemini 3 series LOW tier.
When AI is unavailable, algorithmic fallback kicks in — never crashes.
"""

from fastapi import APIRouter, Depends, Query, Request
from loguru import logger
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.schemas.chat import (
    ChatHistoryResponse,
    ConversationListResponse,
    SendMessageRequest,
    SendMessageResponse,
    TalentReplyRequest,
    TalentReplyResponse,
    UnlockIdentityRequest,
    UnlockIdentityResponse,
)
from app.services.chat_service import (
    get_chat_history,
    get_recruiter_conversations,
    get_talent_conversations,
    send_recruiter_message,
    send_talent_reply,
    unlock_chat_identity,
)
from app.utils.errors import error_response, ErrorCode, raise_error


router = APIRouter(prefix="/v1/chat", tags=["Chat"])


@router.post("/send", response_model=SendMessageResponse)
async def send_message(
    req: Request,
    body: SendMessageRequest,
    db: AsyncSession = Depends(get_db),
):
    """Recruiter sends a message to a talent.
    Message is AI-mediated via Gemini 3.5 Flash (LOW tier).
    """
    recruiter_email = getattr(req.state, "user_email", None)
    if not recruiter_email:
        raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)

    result = await send_recruiter_message(
        db=db,
        recruiter_email=recruiter_email,
        talent_id=body.talent_id,
        raw_message=body.message,
        existing_conversation_id=body.conversation_id,
    )
    return result


@router.post("/reply", response_model=TalentReplyResponse)
async def reply_message(
    req: Request,
    body: TalentReplyRequest,
    db: AsyncSession = Depends(get_db),
):
    """Talent replies to a conversation.
    Reply is AI-summarized for the recruiter via Gemini 3.5 Flash (LOW tier).
    """
    talent_email = getattr(req.state, "user_email", None)
    if not talent_email:
        raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)

    result = await send_talent_reply(
        db=db,
        talent_email=talent_email,
        conversation_id=body.conversation_id,
        raw_reply=body.message,
    )
    return result


@router.post("/unlock", response_model=UnlockIdentityResponse)
async def unlock_identity(
    req: Request,
    body: UnlockIdentityRequest,
    db: AsyncSession = Depends(get_db),
):
    """Unlock talent identity in chat. Costs 5 coins.
    After unlock, all future messages show real names.
    """
    recruiter_email = getattr(req.state, "user_email", None)
    if not recruiter_email:
        raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)

    result = await unlock_chat_identity(
        db=db,
        recruiter_email=recruiter_email,
        talent_id=body.talent_id,
    )
    return result


@router.get("/conversations", response_model=ConversationListResponse)
async def list_conversations(
    req: Request,
    db: AsyncSession = Depends(get_db),
):
    """List conversations for the authenticated recruiter.
    Returns latest message per partner, sorted by time.
    """
    recruiter_email = getattr(req.state, "user_email", None)
    if not recruiter_email:
        raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)

    return await get_recruiter_conversations(db=db, recruiter_email=recruiter_email)


@router.get("/talent/conversations", response_model=ConversationListResponse)
async def list_talent_conversations(
    req: Request,
    db: AsyncSession = Depends(get_db),
):
    """List conversations for the authenticated talent.
    Returns latest message per conversation, sorted by time.
    """
    talent_email = getattr(req.state, "user_email", None)
    if not talent_email:
        raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)

    return await get_talent_conversations(db=db, talent_email=talent_email)


@router.get("/history", response_model=ChatHistoryResponse)
async def chat_history(
    req: Request,
    partner_id: str = Query(..., description="Partner ID (talent email for recruiter, conversation ID for talent)"),
    role: str = Query("RECRUITER", description="Role: RECRUITER or TALENT"),
    db: AsyncSession = Depends(get_db),
):
    """Get full message history for a conversation.
    
    For recruiters: partner_id = talent email
    For talents: partner_id = conversation ID
    """
    user_email = getattr(req.state, "user_email", None)
    if not user_email:
        raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)

    return await get_chat_history(
        db=db,
        email=user_email,
        partner_id=partner_id,
        role=role,
    )