import { Injectable, Logger, NotFoundException, ForbiddenException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { S3Service } from '../s3/s3.service';
import { Document, User, Prisma } from '@prisma/client';

@Injectable()
export class DocumentsService {
  private readonly logger = new Logger(DocumentsService.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly s3Service: S3Service
  ) {}

  async findDocumentByS3Key(s3Key: string) {
    return this.prisma.document.findFirst({
      where: { s3Key },
      include: {
        uploadedBy: true,
        sharedWith: true,
      },
    });
  }

  async verifyDocumentAccess(documentId: number, userId: number): Promise<boolean> {
    const document = await this.prisma.document.findUnique({
      where: { id: documentId },
      include: {
        uploadedBy: true,
        sharedWith: {
          where: {
            id: userId
          }
        }
      },
    });

    if (!document) {
      return false;
    }

    // User has access if they uploaded the document or it's shared with them
    return document.uploadedBy.id === userId || document.sharedWith.length > 0;
  }

  async getClientDocuments(clientId: number) {
    return this.prisma.document.findMany({
      where: {
        OR: [
          { uploadedById: clientId },
          { 
            sharedWith: {
              some: {
                id: clientId
              }
            } 
          }
        ]
      },
      include: {
        uploadedBy: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        sharedWith: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    });
  }

  async uploadDocument(
    file: Express.Multer.File,
    title: string,
    sharedWithId: number,
    uploadedById: number
  ) {
    const s3Key = await this.s3Service.uploadFile(file, 'documents');
    
    return this.prisma.document.create({
      data: {
        title,
        s3Key,
        status: 'pending',
        uploadedBy: {
          connect: { id: uploadedById }
        },
        sharedWith: {
          connect: { id: sharedWithId }
        }
      },
      include: {
        uploadedBy: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
        sharedWith: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
      },
    });
  }
}
