/**
 * Image Service
 * Handles image upload and management
 */

import { prisma } from '../lib/prisma';

export interface CreateImageInput {
  user_id: string;
  file_path: string;
  file_size: number;
  mime_type: string;
  document_id?: string | null;
}

export class ImageService {
  /**
   * Create a new image record
   */
  static async create(input: CreateImageInput) {
    return prisma.image.create({
      data: {
        user_id: input.user_id,
        file_path: input.file_path,
        file_size: input.file_size,
        mime_type: input.mime_type,
        document_id: input.document_id ?? null,
        processing_status: 'pending',
      },
    });
  }

  /**
   * Find image by ID
   */
  static async findById(id: string, userId: string) {
    return prisma.image.findFirst({
      where: {
        id,
        user_id: userId,
      },
    });
  }

  /**
   * Update OCR result
   */
  static async updateOCRResult(id: string, userId: string, text: string, confidence: number) {
    const existing = await this.findById(id, userId);
    if (!existing) {
      throw new Error('Image not found or access denied');
    }

    return prisma.image.update({
      where: { id },
      data: {
        ocr_result: text,
        ocr_confidence: confidence,
        processing_status: confidence >= 0.3 ? 'completed' : 'failed',
      },
    });
  }

  /**
   * Link image to document
   */
  static async linkToDocument(imageId: string, userId: string, documentId: string) {
    const image = await this.findById(imageId, userId);
    if (!image) {
      throw new Error('Image not found or access denied');
    }

    // Verify document belongs to user
    const document = await prisma.document.findFirst({
      where: {
        id: documentId,
        user_id: userId,
      },
    });

    if (!document) {
      throw new Error('Document not found or access denied');
    }

    return prisma.image.update({
      where: { id: imageId },
      data: {
        document_id: documentId,
      },
    });
  }

  /**
   * Get pending images (OCR failed or low confidence)
   */
  static async getPendingImages(userId: string) {
    return prisma.image.findMany({
      where: {
        user_id: userId,
        processing_status: 'failed',
        OR: [
          {
            ocr_confidence: {
              lt: 0.3,
            },
          },
          {
            ocr_confidence: null,
          },
        ],
      },
      orderBy: { created_at: 'desc' },
    });
  }

  /**
   * Find all images for a user
   */
  static async findByUser(userId: string, documentId?: string) {
    const where: any = {
      user_id: userId,
    };

    if (documentId) {
      where.document_id = documentId;
    }

    return prisma.image.findMany({
      where,
      orderBy: { created_at: 'desc' },
    });
  }

  /**
   * Delete image
   */
  static async delete(id: string, userId: string) {
    const existing = await this.findById(id, userId);
    if (!existing) {
      throw new Error('Image not found or access denied');
    }

    await prisma.image.delete({
      where: { id },
    });
  }
}
