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
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks
from sqlalchemy.orm import Session
from sqlalchemy import func
from app.db.session import get_db
from app.schemas import schemas
from app.core.dependencies import admin_only
from app.core import security, config
from app.crud import user as crud_user, setting as crud_setting
from app.models.models import User, Video, View, Challenge, ChallengeEntry, Transaction, PayoutRequest
from fastapi.security import OAuth2PasswordRequestForm
from datetime import timedelta, datetime
from typing import List, Optional
from sqlalchemy import cast, Date
from app.tasks.email_tasks import queue_new_challenge_announcement
from app.services.email_service import send_pro_upgrade_email

router = APIRouter()

@router.options("/login")
async def admin_login_options():
    """Explicit CORS preflight handler — prevents form-body parser from running on OPTIONS."""
    return {}


@router.post("/login", response_model=schemas.Token)

async def login_for_admin_access_token(
    db: Session = Depends(get_db),
    form_data: OAuth2PasswordRequestForm = Depends()
):
    # Support login by username OR email
    user = crud_user.get_user_by_username(db, username=form_data.username)
    if not user:
        user = crud_user.get_user_by_email(db, email=form_data.username)

    if not user or not security.verify_password(form_data.password, user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )

    if user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Access denied: Admin privileges required",
        )

    access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = security.create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer", "username": user.username}


@router.get("/users", response_model=List[schemas.User])
def read_users(
    skip: int = 0, 
    limit: int = 100, 
    db: Session = Depends(get_db),
    current_user: dict = Depends(admin_only)
):
    users = db.query(User).offset(skip).limit(limit).all()
    return users

@router.get("/stats")
def read_stats(
    db: Session = Depends(get_db),
    current_user: dict = Depends(admin_only)
):
    user_count = db.query(func.count(User.id)).scalar() or 0
    video_count = db.query(func.count(Video.id)).scalar() or 0
    premium_count = db.query(func.count(User.id)).filter(User.is_premium == True).scalar() or 0
    
    # Sum views
    total_views_sum = db.query(func.sum(Video.views)).scalar() or 0

    # Total Revenue (Subscriptions)
    total_rev = db.query(func.sum(Transaction.amount)).filter(Transaction.transaction_type == 'pro_subscription').scalar() or 0
    
    # Pending Payouts (Liabilities)
    pending_payouts_sum = db.query(func.sum(PayoutRequest.amount)).filter(PayoutRequest.status == 'pending').scalar() or 0

    # Top Countries Breakdown
    top_signup_countries_query = (
        db.query(User.country, func.count(User.id).label("count"))
        .filter(User.country != None)
        .group_by(User.country)
        .order_by(func.count(User.id).desc())
        .limit(5)
        .all()
    )
    top_signup_countries = [{"country": c, "count": cnt} for c, cnt in top_signup_countries_query]

    return {
        "users": user_count,
        "videos": video_count,
        "premium_users": premium_count,
        "total_views": total_views_sum,
        "total_revenue": float(total_rev),
        "pending_payouts": float(pending_payouts_sum),
        "top_signup_countries": top_signup_countries
    }

@router.post("/promote/{user_id}")
def promote_user(
    user_id: int,
    background_tasks: BackgroundTasks,
    is_premium: bool = True,
    db: Session = Depends(get_db),
    current_user: dict = Depends(admin_only)
):
    user = crud_user.get_user_by_id(db, user_id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    
    was_premium = user.is_premium
    user.is_premium = is_premium
    db.commit()
    db.refresh(user)
    
    if is_premium and not was_premium and user.email:
        background_tasks.add_task(send_pro_upgrade_email, user.email, user.username)
    
    return {"message": f"User {user.username} premium status set to {is_premium}"}

@router.get("/settings/storage-mode")
def get_storage_mode(
    db: Session = Depends(get_db),
    current_user: dict = Depends(admin_only)
):
    mode = crud_setting.get_setting(db, "storage_mode")
    mode = mode or config.STORAGE_MODE
    if mode == "gcs":
        mode = "s3"
    return {"mode": mode}

@router.put("/settings/storage-mode")
def update_storage_mode(
    mode: str,
    db: Session = Depends(get_db),
    current_user: dict = Depends(admin_only)
):
    # Normalize legacy "gcs" label to "s3" (AWS from .env)
    if mode == "gcs":
        mode = "s3"
    if mode not in ["s3", "local"]:
        raise HTTPException(status_code=400, detail="Invalid storage mode")
    
    crud_setting.update_setting(db, "storage_mode", mode)
    return {"message": f"Storage mode updated to {mode}", "mode": mode}

@router.get("/stats/performance")
def get_performance_stats(
    metric: str,
    days: int = 30,
    db: Session = Depends(get_db),
    current_user: dict = Depends(admin_only)
):
    end_date = datetime.utcnow()
    start_date = end_date - timedelta(days=days)
    
    if metric == "users":
        query = db.query(
            func.date(User.created_at).label("date"),
            func.count(User.id).label("value")
        ).filter(User.created_at >= start_date)
    elif metric == "videos":
        query = db.query(
            func.date(Video.created_at).label("date"),
            func.count(Video.id).label("value")
        ).filter(Video.created_at >= start_date)
    elif metric == "premium":
        query = db.query(
            func.date(User.created_at).label("date"),
            func.count(User.id).label("value")
        ).filter(User.created_at >= start_date, User.is_premium == True)
    elif metric == "views":
        query = db.query(
            func.date(View.created_at).label("date"),
            func.count(View.id).label("value")
        ).filter(View.created_at >= start_date)
    elif metric == "revenue":
        query = db.query(
            func.date(Transaction.created_at).label("date"),
            func.sum(Transaction.amount).label("value")
        ).filter(
            Transaction.created_at >= start_date,
            Transaction.transaction_type == 'pro_subscription'
        )
    else:
        raise HTTPException(status_code=400, detail="Invalid metric")

    results = query.group_by("date").order_by("date").all()
    
    return [{"date": str(r.date), "value": float(r.value or 0)} for r in results]

@router.get("/config")
def get_admin_config(
    current_user: dict = Depends(admin_only)
):
    return {
        "rust_service_url": config.RUST_SERVICE_URL
    }

# Challenges Management

@router.get("/challenges", response_model=List[schemas.Challenge])
def read_challenges(
    db: Session = Depends(get_db),
    current_user: dict = Depends(admin_only)
):
    return db.query(Challenge).order_by(Challenge.created_at.desc()).all()

@router.post("/challenges", response_model=schemas.Challenge)
def create_challenge(
    challenge_in: schemas.ChallengeCreate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(admin_only)
):
    db_challenge = Challenge(**challenge_in.model_dump())
    db.add(db_challenge)
    db.commit()
    db.refresh(db_challenge)
    
    # Dispatch Celery background task for email broadcasting
    queue_new_challenge_announcement.delay(db_challenge.id)
    
    return db_challenge

@router.put("/challenges/{challenge_id}", response_model=schemas.Challenge)
def update_challenge(
    challenge_id: int,
    challenge_in: schemas.ChallengeBase, # using base for partial update logic if desired or complete update
    db: Session = Depends(get_db),
    current_user: dict = Depends(admin_only)
):
    db_challenge = db.query(Challenge).filter(Challenge.id == challenge_id).first()
    if not db_challenge:
        raise HTTPException(status_code=404, detail="Challenge not found")
    
    update_data = challenge_in.model_dump(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_challenge, key, value)
    
    db.commit()
    db.refresh(db_challenge)
    return db_challenge

@router.delete("/challenges/{challenge_id}")
def delete_challenge(
    challenge_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(admin_only)
):
    db_challenge = db.query(Challenge).filter(Challenge.id == challenge_id).first()
    if not db_challenge:
        raise HTTPException(status_code=404, detail="Challenge not found")
    
    db.delete(db_challenge)
    db.commit()
    return {"message": "Challenge deleted successfully"}


# Content Reports Admin APIs
from app.schemas.report import ReportResponse, ReportAction, AuditLogResponse
from app.models.models import ContentReport, ModerationAuditLog, Comment, Post

@router.get("/reports", response_model=List[ReportResponse])
def get_reports(
    status: Optional[str] = None,
    content_type: Optional[str] = None,
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user = Depends(admin_only)
):
    query = db.query(ContentReport)
    if status:
        query = query.filter(ContentReport.status == status)
    if content_type:
        query = query.filter(ContentReport.content_type == content_type)
    
    reports = query.order_by(ContentReport.created_at.desc()).offset(skip).limit(limit).all()
    
    response_list = []
    for r in reports:
        reporter_username = r.reporter.username if r.reporter else "Unknown"
        resolver_username = r.resolver.username if r.resolver else None
        
        preview = "Content unavailable"
        creator = "Unknown"
        c_id = r.video_id or r.post_id or r.comment_id or 0
        
        if r.content_type in ["video", "flash"] and r.video:
            preview = r.video.title
            creator = r.video.owner.username if r.video.owner else "Unknown"
            c_id = r.video.public_id if r.video.public_id else str(r.video.id)
        elif r.content_type == "post" and r.post:
            preview = r.post.content[:100] + "..." if len(r.post.content) > 100 else r.post.content
            creator = r.post.owner.username if r.post.owner else "Unknown"
            c_id = r.post.id
        elif r.content_type == "comment" and r.comment:
            preview = r.comment.content[:100] + "..." if len(r.comment.content) > 100 else r.comment.content
            creator = r.comment.owner.username if r.comment.owner else "Unknown"
            c_id = r.comment.id
            
        response_list.append(
            ReportResponse(
                id=r.id,
                reporter_id=r.reporter_id,
                reporter_username=reporter_username,
                content_type=r.content_type,
                content_id=c_id,
                reason=r.reason,
                description=r.description,
                status=r.status,
                created_at=r.created_at,
                resolved_at=r.resolved_at,
                resolved_by=r.resolved_by,
                resolver_username=resolver_username,
                notes=r.notes,
                reported_content_preview=preview,
                reported_content_creator=creator
            )
        )
    return response_list

@router.post("/reports/{report_id}/action")
def take_report_action(
    report_id: int,
    action_in: ReportAction,
    db: Session = Depends(get_db),
    current_user = Depends(admin_only)
):
    report = db.query(ContentReport).filter(ContentReport.id == report_id).first()
    if not report:
        raise HTTPException(status_code=404, detail="Report not found")
        
    action = action_in.action.lower()
    notes = action_in.notes
    
    # Identify content creator
    creator_user = None
    target_id_str = ""
    
    if report.content_type in ["video", "flash"] and report.video:
        creator_user = report.video.owner
        target_id_str = report.video.public_id or str(report.video.id)
    elif report.content_type == "post" and report.post:
        creator_user = report.post.owner
        target_id_str = str(report.post.id)
    elif report.content_type == "comment" and report.comment:
        creator_user = report.comment.owner
        target_id_str = str(report.comment.id)

    # 1. Update Report status
    report.status = "dismissed" if action == "dismiss" else "resolved"
    report.resolved_at = datetime.utcnow()
    report.resolved_by = current_user.id
    report.notes = notes

    # 2. Perform requested Action
    details_str = f"Action taken: {action} by admin: {current_user.username}. Notes: {notes}"
    
    if action == "delete_content":
        if report.content_type in ["video", "flash"] and report.video:
            db.delete(report.video)
        elif report.content_type == "post" and report.post:
            db.delete(report.post)
        elif report.content_type == "comment" and report.comment:
            db.delete(report.comment)
            
    elif action == "suspend_user":
        if creator_user:
            creator_user.is_active = False
            details_str += f" | Suspended user: @{creator_user.username}"
            
    # 3. Create Audit Log
    audit_log = ModerationAuditLog(
        action=f"report_{action}",
        moderator_id=current_user.id,
        target_type=report.content_type,
        target_id=target_id_str,
        details=details_str
    )
    db.add(audit_log)
    db.commit()
    
    return {"message": f"Action '{action}' processed successfully."}

@router.get("/moderation/audit-logs", response_model=List[AuditLogResponse])
def get_moderation_audit_logs(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user = Depends(admin_only)
):
    logs = db.query(ModerationAuditLog).order_by(ModerationAuditLog.created_at.desc()).offset(skip).limit(limit).all()
    
    response_list = []
    for l in logs:
        mod_name = l.moderator.username if l.moderator else "System"
        response_list.append(
            AuditLogResponse(
                id=l.id,
                action=l.action,
                moderator_id=l.moderator_id,
                moderator_username=mod_name,
                target_type=l.target_type,
                target_id=l.target_id,
                details=l.details,
                created_at=l.created_at
            )
        )
    return response_list