import type { Request, Response } from 'express';
import { workNoteService } from '../services/worknote.service';
import { WorkflowService } from '../services/workflow.service';
import { getRequestMetadata } from '@utils/requestUtils';

export class WorkNoteController {
  private workflowService = new WorkflowService();

  async list(req: any, res: Response): Promise<void> {
    const wf = await (this.workflowService as any).findWorkflowByIdentifier(req.params.id);
    if (!wf) { res.status(404).json({ success: false, error: 'Not found' }); return; }
    const requestId: string = wf.getDataValue('requestId');
    const rows = await workNoteService.list(requestId);
    res.json({ success: true, data: rows });
  }

  async create(req: any, res: Response): Promise<void> {
    const wf = await (this.workflowService as any).findWorkflowByIdentifier(req.params.id);
    if (!wf) { res.status(404).json({ success: false, error: 'Not found' }); return; }
    const requestId: string = wf.getDataValue('requestId');
    
    // Get user's participant info (includes userName and role)
    const { Participant } = require('@models/Participant');
    const participant = await Participant.findOne({
      where: { requestId, userId: req.user?.userId }
    });
    
    let userName = req.user?.email || 'Unknown User';
    let userRole = 'SPECTATOR';
    
    if (participant) {
      userName = (participant as any).userName || (participant as any).user_name || req.user?.email || 'Unknown User';
      userRole = (participant as any).participantType || (participant as any).participant_type || 'SPECTATOR';
    }
    
    const user = { 
      userId: req.user?.userId, 
      name: userName,
      role: userRole
    };
    
    const payload = req.body?.payload ? JSON.parse(req.body.payload) : (req.body || {});
    // Map files with buffer for GCS upload (multer.memoryStorage provides buffer, not path)
    const files = (req.files as any[])?.map(f => ({ 
      buffer: f.buffer, 
      path: f.path || null, // May not exist with memory storage
      originalname: f.originalname, 
      mimetype: f.mimetype, 
      size: f.size 
    })) || [];
    
    // Extract mentions from payload (sent by frontend)
    const mentions = payload.mentions || [];
    const workNotePayload = {
      message: payload.message,
      isPriority: payload.isPriority,
      parentNoteId: payload.parentNoteId,
      mentionedUsers: mentions // Pass mentioned user IDs to service
    };
    
    const requestMeta = getRequestMetadata(req);
    const note = await workNoteService.create(requestId, user, workNotePayload, files, {
      ipAddress: requestMeta.ipAddress,
      userAgent: requestMeta.userAgent
    });
    res.status(201).json({ success: true, data: note });
  }
}


