import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../infrastructure/database/prisma.service';

@Injectable()
export class TemporaryReadingMaterialService {
  constructor(private readonly prisma: PrismaService) {}

  async create(data: {
    userId: string;
    title?: string;
    originalFilename?: string;
    mimeType?: string;
    sizeBytes?: number;
    storageKey?: string;
    expiresAt?: Date;
  }) {
    return this.prisma.temporaryReadingMaterial.create({
      data: {
        userId: data.userId,
        title: data.title ?? null,
        originalFilename: data.originalFilename ?? null,
        mimeType: data.mimeType ?? null,
        sizeBytes: BigInt(data.sizeBytes ?? 0),
        storageKey: data.storageKey ?? null,
        expiresAt: data.expiresAt ?? null,
      },
    });
  }

  /** Validate a material is active and belongs to user. Returns null if invalid. */
  async validateAccess(userId: string, materialId: string) {
    const mat = await this.prisma.temporaryReadingMaterial.findUnique({
      where: { id: materialId },
    });

    if (!mat) return null;
    if (mat.userId !== userId) return null;
    if (mat.deletedAt) return null;
    if (mat.expiresAt && mat.expiresAt < new Date()) {
      // Mark source as expired
      await this.prisma.temporaryReadingMaterial.update({
        where: { id: materialId },
        data: { sourceStatus: 'expired' },
      });
      return null;
    }
    if (mat.sourceStatus === 'expired') return null;

    return mat;
  }
}
