import { BadRequestException, Injectable, NotFoundException, PayloadTooLargeException } from '@nestjs/common';
import * as crypto from 'crypto';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { assertCanDelete, rethrowRelationConflict, type CrmActor } from '../../common/crm/crm-record.helper';
import { ListFilesQuery } from './dto/list-files.query';

export const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB per plan.md §3.2
const NOT_FOUND = 'File not found';

export interface UploadedMulterFile {
  fieldname: string;
  originalname: string;
  encoding: string;
  mimetype: string;
  size: number;
  buffer: Buffer;
}

export const fileMetadataSelect = {
  id: true,
  fileName: true,
  mimeType: true,
  sizeBytes: true,
  description: true,
  checksumSha256: true,
  scanStatus: true,
  uploadedById: true,
  leadId: true,
  contactId: true,
  accountId: true,
  dealId: true,
  projectId: true,
  createdAt: true,
  uploadedBy: { select: { id: true, name: true, email: true } },
  lead: { select: { id: true, name: true, company: true } },
  contact: { select: { id: true, name: true, email: true } },
  account: { select: { id: true, name: true } },
  deal: { select: { id: true, title: true, dealNumber: true } },
  project: { select: { id: true, name: true } },
} satisfies Prisma.FileSelect;

@Injectable()
export class FilesService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
  ) {}

  // Returns paginated file metadata matching linked entity and filename filters.
  async list(ctx: RequestTenantContext, q: ListFilesQuery) {
    const page = Math.max(1, q.page ?? 1);
    const limit = Math.min(100, Math.max(1, q.limit ?? 50));
    const skip = (page - 1) * limit;

    const where: Prisma.FileWhereInput = this.tenant.scopeWhere(ctx, {
      ...(q.leadId ? { leadId: q.leadId } : {}),
      ...(q.contactId ? { contactId: q.contactId } : {}),
      ...(q.accountId ? { accountId: q.accountId } : {}),
      ...(q.dealId ? { dealId: q.dealId } : {}),
      ...(q.projectId ? { projectId: q.projectId } : {}),
      ...(q.q
        ? {
            OR: [{ fileName: { contains: q.q } }, { description: { contains: q.q } }],
          }
        : {}),
    });

    const [items, total] = await Promise.all([
      this.prisma.file.findMany({
        where,
        select: fileMetadataSelect,
        orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
        skip,
        take: limit,
      }),
      this.prisma.file.count({ where }),
    ]);

    return {
      data: items,
      meta: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit) || 1,
      },
    };
  }

  // Retrieves file metadata by ID within tenant scope.
  async getMetadata(ctx: RequestTenantContext, id: string) {
    const file = await this.prisma.file.findFirst({
      where: this.tenant.scopeWhere(ctx, { id }),
      select: fileMetadataSelect,
    });
    if (!file) throw new NotFoundException(NOT_FOUND);
    return file;
  }

  // Validates and saves an uploaded file and its binary payload transactionally.
  async upload(
    ctx: RequestTenantContext,
    file: UploadedMulterFile,
    links: {
      leadId?: string;
      contactId?: string;
      accountId?: string;
      dealId?: string;
      projectId?: string;
      description?: string;
    },
  ) {
    if (!file || !file.buffer) {
      throw new BadRequestException('No file uploaded');
    }

    if (file.size > MAX_FILE_SIZE) {
      throw new PayloadTooLargeException('File size exceeds the 10 MB limit');
    }

    const checksumSha256 = crypto.createHash('sha256').update(file.buffer).digest('hex');

    try {
      return await this.prisma.$transaction(async (tx) => {
        const record = await tx.file.create({
          data: this.tenant.scopeCreate(ctx, {
            fileName: file.originalname,
            mimeType: file.mimetype || 'application/octet-stream',
            sizeBytes: file.size,
            description: links.description?.trim() || null,
            checksumSha256,
            uploadedById: ctx.userId,
            leadId: links.leadId || null,
            contactId: links.contactId || null,
            accountId: links.accountId || null,
            dealId: links.dealId || null,
            projectId: links.projectId || null,
          }),
          select: fileMetadataSelect,
        });

        await tx.fileContent.create({
          data: {
            fileId: record.id,
            bytes: new Uint8Array(file.buffer),
          },
        });

        return record;
      });
    } catch (err) {
      rethrowRelationConflict(err, 'Linked record does not exist');
    }
  }

  // Retrieves file metadata and binary content bytes for download.
  async download(ctx: RequestTenantContext, id: string) {
    const metadata = await this.getMetadata(ctx, id);

    const content = await this.prisma.fileContent.findUnique({
      where: { fileId: id },
    });
    if (!content) throw new NotFoundException('File content not found');

    return {
      metadata,
      bytes: content.bytes,
    };
  }

  // Deletes file metadata and binary content within tenant scope.
  async remove(ctx: RequestTenantContext, actor: CrmActor, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    assertCanDelete(actor);
    await this.getMetadata(ctx, id);
    await this.prisma.file.delete({
      where: { tenantId_id: { tenantId, id } },
    });
    return { success: true };
  }
}
