/**
 * Admin Notes Service
 *
 * Handles creation and retrieval of admin notes for user accounts.
 *
 * @module services/admin-notes
 */

import { prisma } from '@/lib/db';
import { adminNotesAdapter } from '@/lib/adapters/admin';
import type { AdminNote, CreateAdminNoteRequest } from '@/lib/types/user-management.types';
import { QUERY_LIMITS } from '@/lib/constants/user-management.constants';

/**
 * Admin Notes Service Class
 *
 * Provides methods for managing admin notes on user accounts
 */
export class AdminNotesService {
  /**
   * Create a new admin note for a user
   *
   * @param userId - User ID to add note to
   * @param staffId - Staff member creating the note
   * @param noteData - Note content and metadata
   * @returns Created admin note
   *
   * @example
   * const note = await service.createNote('user-123', 'staff-456', {
   *   content: 'Customer inquired about pricing',
   *   category: 'SUPPORT',
   *   isPrivate: true
   * });
   */
  async createNote(
    userId: string,
    staffId: string,
    noteData: CreateAdminNoteRequest
  ): Promise<AdminNote> {
    const { content, category, isPrivate = true } = noteData;

    // Verify user exists
    const userExists = await this.verifyUserExists(userId);
    if (!userExists) {
      throw new Error('User not found');
    }

    // Create note in Prisma (primary database)
    const note = await adminNotesAdapter.create({
      data: {
        userId,
        staffId,
        content,
        category,
        isPrivate,
      },
    });

    console.log(`Admin note created: ${note.id} by staff ${staffId} for user ${userId}`);

    return note;
  }

  /**
   * Get all admin notes for a user
   *
   * @param userId - User ID
   * @param limit - Maximum number of notes to return
   * @returns Array of admin notes
   *
   * @example
   * const notes = await service.getNotesByUser('user-123', 50);
   */
  async getNotesByUser(userId: string, limit: number = QUERY_LIMITS.ADMIN_NOTES): Promise<AdminNote[]> {
    const notes = await adminNotesAdapter.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
      take: limit,
    });

    return notes;
  }

  /**
   * Get notes by category for a user
   *
   * @param userId - User ID
   * @param category - Note category
   * @returns Array of notes in that category
   */
  async getNotesByCategory(
    userId: string,
    category: string
  ): Promise<AdminNote[]> {
    const notes = await adminNotesAdapter.findMany({
      where: {
        userId,
        category: category as any,
      },
      orderBy: { createdAt: 'desc' },
    });

    return notes;
  }

  /**
   * Get total note count for a user
   *
   * @param userId - User ID
   * @returns Number of notes
   */
  async getNoteCount(userId: string): Promise<number> {
    return await adminNotesAdapter.count({
      where: { userId },
    });
  }

  /**
   * Delete an admin note
   *
   * @param noteId - Note ID to delete
   * @param staffId - Staff member performing deletion
   * @returns Success boolean
   */
  async deleteNote(noteId: string, staffId: string): Promise<boolean> {
    try {
      // Delete from Prisma
      await adminNotesAdapter.delete({
        where: { id: noteId },
      });

      console.log(`Admin note deleted: ${noteId} by staff ${staffId}`);
      return true;
    } catch (error) {
      console.error('Failed to delete admin note:', error);
      return false;
    }
  }

  // ============================================
  // PRIVATE HELPER METHODS
  // ============================================

  /**
   * Verify user exists before creating note
   * @private
   */
  private async verifyUserExists(userId: string): Promise<boolean> {
    const user = await prisma.users.findUnique({
      where: { id: userId },
      select: { id: true },
    });

    return !!user;
  }

}

// Export singleton instance
export const adminNotesService = new AdminNotesService();
