import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { S3Service } from '../s3/s3.service';
import { UpdateDocumentDto } from '../dto/update-document.dto';
import { CreateUserDto } from '../dto/create-user.dto';
import * as bcrypt from 'bcrypt';

@Injectable()
export class AdminService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly s3Service: S3Service,
  ) {}

  async getAllDocuments() {
    return this.prisma.document.findMany({
      include: {
        uploadedBy: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
        sharedWith: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });
  }

  async getAllUsers() {
    return this.prisma.user.findMany();
  }

  async createUser(createUserDto: CreateUserDto) {
    const hashedPassword = await bcrypt.hash(createUserDto.password, 10);

    return this.prisma.user.create({
      data: {
        ...createUserDto,
        password: hashedPassword,
      },
    });
  }

  async updateDocument(
    id: number,
    updateDocumentDto: UpdateDocumentDto,
    file?: Express.Multer.File,
  ) {
    let s3Key = undefined;
    if (file) {
      s3Key = await this.s3Service.uploadFile(file, 'documents');
    }

    return this.prisma.document.update({
      where: { id },
      data: {
        ...updateDocumentDto,
        ...(s3Key && { s3Key }),
      },
    });
  }

  async shareDocument(documentId: number, userId: number) {
    return this.prisma.document.update({
      where: { id: documentId },
      data: {
        sharedWith: {
          connect: { id: userId },
        },
      },
    });
  }

  async updateDocumentStatus(documentId: number, status: string) {
    return this.prisma.document.update({
      where: { id: documentId },
      data: { status },
    });
  }

  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',
        sharedWith: {
          connect: { id: sharedWithId }
        },
        uploadedBy: {
          connect: { id: uploadedById }
        }
      },
      include: {
        uploadedBy: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
        sharedWith: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
      },
    });
  }
}