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 
 
 
 
 
 
 
 
 
 
 
 
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
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
"""
Document Management Endpoints
Universal document upload and management for all entities
"""
from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Form, Request
from sqlalchemy.orm import Session
from typing import List, Optional
from uuid import UUID

from app.api.deps import get_db, get_current_active_user
from app.models.user import User
from app.models.document import Document
from app.models.user_document_link import UserDocumentLink
from app.schemas.document import (
    DocumentResponse,
    DocumentListResponse,
    DocumentUpdateRequest,
    UploaderInfo
)
from app.services.media_service import StorageService
from app.services.audit_service import AuditService
from app.core.permissions import require_permission, require_any_permission
from datetime import datetime
import logging
import json

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/documents", tags=["Document Management"])


# ============================================
# SPECIFIC ROUTES (Must come before generic parameterized routes)
# ============================================

# Current user document endpoints
@router.get("/users/me", response_model=DocumentListResponse)
async def get_my_documents(
    document_type: Optional[str] = None,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """Get current user's documents"""
    query = db.query(Document).filter(
        Document.entity_type == "user",
        Document.entity_id == current_user.id,
        Document.deleted_at == None
    )
    
    if document_type:
        query = query.filter(Document.document_type == document_type)
    
    documents = query.order_by(Document.created_at.desc()).all()
    
    # Enrich with uploader info and generate fresh signed URLs for Supabase files
    from app.integrations.supabase import SupabaseStorageService
    response_docs = []
    for doc in documents:
        doc_response = DocumentResponse.from_orm(doc)
        
        # Generate fresh signed URL for Supabase files
        if doc.storage_provider == 'supabase' and doc.file_url.startswith('supabase://'):
            bucket = doc.additional_metadata.get('bucket')
            path = doc.additional_metadata.get('path')
            if bucket and path:
                doc_response.file_url = SupabaseStorageService.get_signed_url(bucket, path, 3600)
        
        if doc.uploaded_by_user_id:
            uploader = db.query(User).filter(User.id == doc.uploaded_by_user_id).first()
            if uploader:
                doc_response.uploader = UploaderInfo(
                    id=uploader.id,
                    name=uploader.name,
                    email=uploader.email
                )
        response_docs.append(doc_response)
    
    return DocumentListResponse(
        total=len(response_docs),
        documents=response_docs
    )


@router.get("/users/me/profile-photo", response_model=Optional[DocumentResponse])
async def get_my_profile_photo(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """Get current user's profile photo"""
    doc_link = db.query(UserDocumentLink).filter(
        UserDocumentLink.user_id == current_user.id,
        UserDocumentLink.document_link_type == 'profile_photo'
    ).first()
    
    if not doc_link:
        return None
    
    document = db.query(Document).filter(
        Document.id == doc_link.document_id,
        Document.deleted_at == None
    ).first()
    
    if not document:
        return None
    
    response = DocumentResponse.from_orm(document)
    
    # Generate fresh signed URL for Supabase files
    if document.storage_provider == 'supabase' and document.file_url.startswith('supabase://'):
        from app.integrations.supabase import SupabaseStorageService
        bucket = document.additional_metadata.get('bucket')
        path = document.additional_metadata.get('path')
        if bucket and path:
            response.file_url = SupabaseStorageService.get_signed_url(bucket, path, 3600)
    
    if document.uploaded_by_user_id:
        uploader = db.query(User).filter(User.id == document.uploaded_by_user_id).first()
        if uploader:
            response.uploader = UploaderInfo(
                id=uploader.id,
                name=uploader.name,
                email=uploader.email
            )
    
    return response


# ============================================
# UNIVERSAL DOCUMENT ENDPOINTS
# ============================================

@router.post("/upload", response_model=DocumentResponse, status_code=status.HTTP_201_CREATED)
@require_permission("upload_documents")
async def upload_document(
    file: UploadFile = File(...),
    entity_type: str = Form(...),
    entity_id: str = Form(...),
    document_type: str = Form(...),
    document_category: Optional[str] = Form(None),
    description: Optional[str] = Form(None),
    tags: Optional[str] = Form("[]"),  # JSON string of array
    is_public: bool = Form(False),
    force_provider: Optional[str] = Form(None),  # Optional: 'cloudinary' or 'supabase'
    request: Request = None,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    Universal document upload endpoint with smart fallback
    
    Default routing:
    - Images/videos → Cloudinary (with Supabase fallback)
    - Documents → Supabase Storage
    
    Features:
    - Automatic fallback if primary provider fails
    - Optional provider override via force_provider parameter
    - Supports all entity types: user, project, ticket, client, contractor, etc.
    
    Parameters:
    - force_provider: Optional override ('cloudinary' or 'supabase')
    """
    try:
        # Parse tags from JSON string
        tags_list = json.loads(tags) if tags else []
        
        # Validate file
        if not file.filename:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="No file provided"
            )
        
        # Validate force_provider if provided
        if force_provider and force_provider not in ['cloudinary', 'supabase']:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="force_provider must be 'cloudinary' or 'supabase'"
            )
        
        # Upload file
        document = await StorageService.upload_file(
            file=file,
            entity_type=entity_type,
            entity_id=UUID(entity_id),
            document_type=document_type,
            document_category=document_category,
            description=description,
            tags=tags_list,
            is_public=is_public,
            uploaded_by_user_id=current_user.id,
            db=db,
            force_provider=force_provider
        )
        
        # Create user_document_link for user documents
        if entity_type == 'user':
            # Check if link already exists for this document type
            existing_link = db.query(UserDocumentLink).filter(
                UserDocumentLink.user_id == entity_id,
                UserDocumentLink.document_link_type == document_type
            ).first()
            
            if existing_link:
                # Update existing link to point to new document
                existing_link.document_id = document.id
                existing_link.updated_at = datetime.utcnow().isoformat()
            else:
                # Create new link
                doc_link = UserDocumentLink(
                    user_id=entity_id,
                    document_id=document.id,
                    document_link_type=document_type,
                    notes=description
                )
                db.add(doc_link)
            
            db.commit()
            logger.info(f"Created user_document_link for {document_type}")
        
        # Audit log
        AuditService.log_action(
            db=db,
            action='create',
            entity_type='document',
            entity_id=str(document.id),
            description=f"Uploaded document: {file.filename} for {entity_type}:{entity_id}",
            user=current_user,
            request=request,
            additional_metadata={
                'file_name': file.filename,
                'file_type': file.content_type,
                'storage_provider': document.storage_provider
            }
        )
        
        # Get uploader info
        uploader = db.query(User).filter(User.id == document.uploaded_by_user_id).first()
        
        response = DocumentResponse.from_orm(document)
        if uploader:
            response.uploader = UploaderInfo(
                id=uploader.id,
                name=uploader.name,
                email=uploader.email
            )
        
        return response
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Upload failed: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Upload failed: {str(e)}"
        )


@router.get("/{entity_type}/{entity_id}", response_model=DocumentListResponse)
@require_permission("view_documents")
async def get_entity_documents(
    entity_type: str,
    entity_id: UUID,
    document_type: Optional[str] = None,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    Get all documents for a specific entity
    
    Optional filtering by document_type
    """
    query = db.query(Document).filter(
        Document.entity_type == entity_type,
        Document.entity_id == entity_id,
        Document.deleted_at == None
    )
    
    if document_type:
        query = query.filter(Document.document_type == document_type)
    
    documents = query.order_by(Document.created_at.desc()).all()
    
    # Enrich with uploader info and generate fresh signed URLs for Supabase files
    from app.integrations.supabase import SupabaseStorageService
    response_docs = []
    for doc in documents:
        doc_response = DocumentResponse.from_orm(doc)
        
        # Generate fresh signed URL for Supabase files
        if doc.storage_provider == 'supabase' and doc.file_url.startswith('supabase://'):
            bucket = doc.additional_metadata.get('bucket')
            path = doc.additional_metadata.get('path')
            if bucket and path:
                doc_response.file_url = SupabaseStorageService.get_signed_url(bucket, path, 3600)
        
        if doc.uploaded_by_user_id:
            uploader = db.query(User).filter(User.id == doc.uploaded_by_user_id).first()
            if uploader:
                doc_response.uploader = UploaderInfo(
                    id=uploader.id,
                    name=uploader.name,
                    email=uploader.email
                )
        response_docs.append(doc_response)
    
    return DocumentListResponse(
        total=len(response_docs),
        documents=response_docs
    )


@router.get("/id/{document_id}", response_model=DocumentResponse)
async def get_document(
    document_id: UUID,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """Get single document by ID with fresh signed URL for Supabase files"""
    document = db.query(Document).filter(
        Document.id == document_id,
        Document.deleted_at == None
    ).first()
    
    if not document:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Document not found"
        )
    
    response = DocumentResponse.from_orm(document)
    
    # Generate fresh signed URL for Supabase files
    if document.storage_provider == 'supabase' and document.file_url.startswith('supabase://'):
        from app.integrations.supabase import SupabaseStorageService
        bucket = document.additional_metadata.get('bucket')
        path = document.additional_metadata.get('path')
        if bucket and path:
            # Generate signed URL valid for 1 hour
            response.file_url = SupabaseStorageService.get_signed_url(bucket, path, 3600)
    
    # Add uploader info
    if document.uploaded_by_user_id:
        uploader = db.query(User).filter(User.id == document.uploaded_by_user_id).first()
        if uploader:
            response.uploader = UploaderInfo(
                id=uploader.id,
                name=uploader.name,
                email=uploader.email
            )
    
    return response


@router.put("/id/{document_id}", response_model=DocumentResponse)
async def update_document_metadata(
    document_id: UUID,
    data: DocumentUpdateRequest,
    request: Request,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """Update document metadata (not the file itself)"""
    document = db.query(Document).filter(
        Document.id == document_id,
        Document.deleted_at == None
    ).first()
    
    if not document:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Document not found"
        )
    
    # Update fields
    for field, value in data.dict(exclude_unset=True).items():
        setattr(document, field, value)
    
    from datetime import datetime, timezone
    document.updated_at = datetime.now(timezone.utc).isoformat()
    
    db.commit()
    db.refresh(document)
    
    # Audit log
    AuditService.log_action(
        db=db,
        action='update',
        entity_type='document',
        entity_id=str(document.id),
        description=f"Updated document metadata: {document.file_name}",
        user=current_user,
        request=request
    )
    
    return DocumentResponse.from_orm(document)


@router.delete("/id/{document_id}", status_code=status.HTTP_204_NO_CONTENT)
@require_permission("upload_documents")  # Same permission as upload (can manage own documents)
async def delete_document(
    document_id: UUID,
    request: Request,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """Delete document (soft delete in DB, actual file deletion from storage)"""
    document = db.query(Document).filter(
        Document.id == document_id,
        Document.deleted_at == None
    ).first()
    
    if not document:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Document not found"
        )
    
    # Delete file
    success = StorageService.delete_file(document, db)
    
    if not success:
        logger.warning(f"Failed to delete file from storage: {document.file_url}")
    
    # Audit log
    AuditService.log_action(
        db=db,
        action='delete',
        entity_type='document',
        entity_id=str(document.id),
        description=f"Deleted document: {document.file_name}",
        user=current_user,
        request=request
    )


# ============================================
# CONVENIENCE ENDPOINTS (Shortcuts)
# ============================================

    
    # Get document
    document = db.query(Document).filter(
        Document.id == doc_link.document_id,
        Document.deleted_at == None
    ).first()
    
    if not document:
        return None
    
    response = DocumentResponse.from_orm(document)
    
    # Generate fresh signed URL for Supabase files
    if document.storage_provider == 'supabase' and document.file_url.startswith('supabase://'):
        from app.integrations.supabase import SupabaseStorageService
        bucket = document.additional_metadata.get('bucket')
        path = document.additional_metadata.get('path')
        if bucket and path:
            response.file_url = SupabaseStorageService.get_signed_url(bucket, path, 3600)
    
    # Add uploader info
    if document.uploaded_by_user_id:
        uploader = db.query(User).filter(User.id == document.uploaded_by_user_id).first()
        if uploader:
            response.uploader = UploaderInfo(
                id=uploader.id,
                name=uploader.name,
                email=uploader.email
            )
    
    return response


@router.get("/users/{user_id}", response_model=DocumentListResponse)
async def get_user_documents(
    user_id: UUID,
    document_type: Optional[str] = None,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    Get another user's documents
    
    Requires permission to view the user (same org or shared projects)
    """
    # Check if user exists and current user has permission
    target_user = db.query(User).filter(
        User.id == user_id,
        User.deleted_at == None
    ).first()
    
    if not target_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    
    # Permission check (same logic as GET /users/{user_id})
    has_permission = False
    
    if current_user.role == 'platform_admin':
        has_permission = True
    elif current_user.id == user_id:
        has_permission = True
    elif current_user.role in ['client_admin', 'contractor_admin']:
        if current_user.client_id and current_user.client_id == target_user.client_id:
            has_permission = True
        if current_user.contractor_id and current_user.contractor_id == target_user.contractor_id:
            has_permission = True
    elif current_user.role in ['project_manager', 'sales_manager', 'dispatcher']:
        if current_user.client_id and current_user.client_id == target_user.client_id:
            has_permission = True
        if current_user.contractor_id and current_user.contractor_id == target_user.contractor_id:
            has_permission = True
    
    if not has_permission:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You don't have permission to view this user's documents"
        )
    
    # Get documents
    query = db.query(Document).filter(
        Document.entity_type == "user",
        Document.entity_id == user_id,
        Document.deleted_at == None
    )
    
    if document_type:
        query = query.filter(Document.document_type == document_type)
    
    documents = query.order_by(Document.created_at.desc()).all()
    
    # Enrich with uploader info and generate fresh signed URLs
    from app.integrations.supabase import SupabaseStorageService
    response_docs = []
    for doc in documents:
        doc_response = DocumentResponse.from_orm(doc)
        
        # Generate fresh signed URL for Supabase files
        if doc.storage_provider == 'supabase' and doc.file_url.startswith('supabase://'):
            bucket = doc.additional_metadata.get('bucket')
            path = doc.additional_metadata.get('path')
            if bucket and path:
                doc_response.file_url = SupabaseStorageService.get_signed_url(bucket, path, 3600)
        
        if doc.uploaded_by_user_id:
            uploader = db.query(User).filter(User.id == doc.uploaded_by_user_id).first()
            if uploader:
                doc_response.uploader = UploaderInfo(
                    id=uploader.id,
                    name=uploader.name,
                    email=uploader.email
                )
        response_docs.append(doc_response)
    
    return DocumentListResponse(
        total=len(response_docs),
        documents=response_docs
    )


@router.get("/users/{user_id}/profile-photo", response_model=Optional[DocumentResponse])
async def get_user_profile_photo(
    user_id: UUID,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    Get user's profile photo (convenience endpoint)
    
    Uses user_document_links for fast lookup
    """
    # Get profile photo link
    doc_link = db.query(UserDocumentLink).filter(
        UserDocumentLink.user_id == user_id,
        UserDocumentLink.document_link_type == 'profile_photo'
    ).first()
    
    if not doc_link:
        return None
    
    # Get document
    document = db.query(Document).filter(
        Document.id == doc_link.document_id,
        Document.deleted_at == None
    ).first()
    
    if not document:
        return None
    
    response = DocumentResponse.from_orm(document)
    
    # Generate fresh signed URL for Supabase files
    if document.storage_provider == 'supabase' and document.file_url.startswith('supabase://'):
        from app.integrations.supabase import SupabaseStorageService
        bucket = document.additional_metadata.get('bucket')
        path = document.additional_metadata.get('path')
        if bucket and path:
            response.file_url = SupabaseStorageService.get_signed_url(bucket, path, 3600)
    
    # Add uploader info
    if document.uploaded_by_user_id:
        uploader = db.query(User).filter(User.id == document.uploaded_by_user_id).first()
        if uploader:
            response.uploader = UploaderInfo(
                id=uploader.id,
                name=uploader.name,
                email=uploader.email
            )
    
    return response



# ============================================
# DOCUMENT VERSIONING ENDPOINTS
# ============================================

@router.get("/{entity_type}/{entity_id}/{document_type}/versions", response_model=List[DocumentResponse])
async def get_document_versions(
    entity_type: str,
    entity_id: UUID,
    document_type: str,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    Get all versions of a document
    
    Returns documents ordered by version (newest first)
    """
    from app.services.media_service import StorageService
    
    documents = StorageService.get_document_versions(
        entity_type=entity_type,
        entity_id=entity_id,
        document_type=document_type,
        db=db
    )
    
    # Enrich with uploader info and generate fresh signed URLs
    from app.integrations.supabase import SupabaseStorageService
    response_docs = []
    for doc in documents:
        doc_response = DocumentResponse.from_orm(doc)
        
        # Generate fresh signed URL for Supabase files
        if doc.storage_provider == 'supabase' and doc.file_url.startswith('supabase://'):
            bucket = doc.additional_metadata.get('bucket')
            path = doc.additional_metadata.get('path')
            if bucket and path:
                doc_response.file_url = SupabaseStorageService.get_signed_url(bucket, path, 3600)
        
        if doc.uploaded_by_user_id:
            uploader = db.query(User).filter(User.id == doc.uploaded_by_user_id).first()
            if uploader:
                doc_response.uploader = UploaderInfo(
                    id=uploader.id,
                    name=uploader.name,
                    email=uploader.email
                )
        response_docs.append(doc_response)
    
    return response_docs


@router.get("/{entity_type}/{entity_id}/{document_type}/latest", response_model=Optional[DocumentResponse])
async def get_latest_document(
    entity_type: str,
    entity_id: UUID,
    document_type: str,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    Get latest version of a document
    """
    from app.services.media_service import StorageService
    
    document = StorageService.get_latest_document(
        entity_type=entity_type,
        entity_id=entity_id,
        document_type=document_type,
        db=db
    )
    
    if not document:
        return None
    
    response = DocumentResponse.from_orm(document)
    
    # Generate fresh signed URL for Supabase files
    if document.storage_provider == 'supabase' and document.file_url.startswith('supabase://'):
        from app.integrations.supabase import SupabaseStorageService
        bucket = document.additional_metadata.get('bucket')
        path = document.additional_metadata.get('path')
        if bucket and path:
            response.file_url = SupabaseStorageService.get_signed_url(bucket, path, 3600)
    
    # Add uploader info
    if document.uploaded_by_user_id:
        uploader = db.query(User).filter(User.id == document.uploaded_by_user_id).first()
        if uploader:
            response.uploader = UploaderInfo(
                id=uploader.id,
                name=uploader.name,
                email=uploader.email
            )
    
    return response


# ============================================
# PROFILE PHOTO SHORTCUTS
# ============================================

@router.post("/users/me/profile-photo", response_model=DocumentResponse, status_code=status.HTTP_201_CREATED)
async def upload_my_profile_photo(
    file: UploadFile = File(...),
    request: Request = None,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    Upload or update current user's profile photo
    
    Automatically creates new version and marks old photo as outdated.
    Profile photos are stored in Cloudinary for optimization.
    """
    # Validate file is an image
    if not file.content_type.startswith('image/'):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Profile photo must be an image"
        )
    
    # Upload with versioning enabled (force Cloudinary for profile photos)
    document = await StorageService.upload_file(
        file=file,
        entity_type="user",
        entity_id=current_user.id,
        document_type="profile_photo",
        document_category="profile",
        description="User profile photo",
        tags=["profile", "photo"],
        is_public=True,
        uploaded_by_user_id=current_user.id,
        db=db,
        force_provider="cloudinary",  # Force Cloudinary for profile photos
        enable_versioning=True
    )
    
    # Update user_document_link
    from app.models.user_document_link import UserDocumentLink
    existing_link = db.query(UserDocumentLink).filter(
        UserDocumentLink.user_id == current_user.id,
        UserDocumentLink.document_link_type == 'profile_photo'
    ).first()
    
    if existing_link:
        existing_link.document_id = document.id
        existing_link.updated_at = datetime.utcnow().isoformat()
    else:
        doc_link = UserDocumentLink(
            user_id=current_user.id,
            document_id=document.id,
            document_link_type='profile_photo',
            notes="Profile photo"
        )
        db.add(doc_link)
    
    db.commit()
    
    # Audit log
    AuditService.log_action(
        db=db,
        action='upload',
        entity_type='document',
        entity_id=str(document.id),
        description=f"Profile photo uploaded for user {current_user.id}",
        user=current_user,
        request=request,
        additional_metadata={
            'document_type': 'profile_photo',
            'version': document.version
        }
    )
    
    # Get uploader info
    response = DocumentResponse.from_orm(document)
    response.uploader = UploaderInfo(
        id=current_user.id,
        name=current_user.name,
        email=current_user.email
    )
    
    return response


@router.post("/users/{user_id}/profile-photo", response_model=DocumentResponse, status_code=status.HTTP_201_CREATED)
async def upload_profile_photo(
    user_id: UUID,
    file: UploadFile = File(...),
    request: Request = None,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    Upload or update user profile photo (admin/manager)
    
    Automatically creates new version and marks old photo as outdated.
    Profile photos are stored in Cloudinary for optimization.
    """
    # Validate file is an image
    if not file.content_type.startswith('image/'):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Profile photo must be an image"
        )
    
    # Upload with versioning enabled (force Cloudinary for profile photos)
    document = await StorageService.upload_file(
        file=file,
        entity_type="user",
        entity_id=user_id,
        document_type="profile_photo",
        document_category="profile",
        description="User profile photo",
        tags=["profile", "photo"],
        is_public=True,
        uploaded_by_user_id=current_user.id,
        db=db,
        force_provider="cloudinary",  # Force Cloudinary for profile photos
        enable_versioning=True
    )
    
    # Update user_document_link
    from app.models.user_document_link import UserDocumentLink
    existing_link = db.query(UserDocumentLink).filter(
        UserDocumentLink.user_id == user_id,
        UserDocumentLink.document_link_type == 'profile_photo'
    ).first()
    
    if existing_link:
        existing_link.document_id = document.id
        existing_link.updated_at = datetime.utcnow().isoformat()
    else:
        doc_link = UserDocumentLink(
            user_id=user_id,
            document_id=document.id,
            document_link_type='profile_photo',
            notes="Profile photo"
        )
        db.add(doc_link)
    
    db.commit()
    
    # Audit log
    AuditService.log_action(
        db=db,
        action='upload',
        entity_type='document',
        entity_id=str(document.id),
        description=f"Profile photo uploaded for user {user_id}",
        user=current_user,
        request=request,
        additional_metadata={
            'document_type': 'profile_photo',
            'version': document.version
        }
    )
    
    # Get uploader info
    response = DocumentResponse.from_orm(document)
    response.uploader = UploaderInfo(
        id=current_user.id,
        name=current_user.name,
        email=current_user.email
    )
    
    return response


@router.get("/users/me/profile-photo/versions", response_model=List[DocumentResponse])
async def get_my_profile_photo_versions(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    Get all versions of current user's profile photo
    """
    return await get_document_versions(
        entity_type="user",
        entity_id=current_user.id,
        document_type="profile_photo",
        current_user=current_user,
        db=db
    )


@router.get("/users/{user_id}/profile-photo/versions", response_model=List[DocumentResponse])
async def get_profile_photo_versions(
    user_id: UUID,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    Get all versions of user's profile photo
    """
    return await get_document_versions(
        entity_type="user",
        entity_id=user_id,
        document_type="profile_photo",
        current_user=current_user,
        db=db
    )