// src/services/ticketService.js
import { getServiceChannelToken } from '../integrations/serviceChannel/client.js';
import axios from 'axios';
import { loadSecrets } from '../config/secrets.js';
import { summarizeTicketWithGrokFromContext } from '../integrations/xai/client.js';

const secrets = loadSecrets();

export async function getTicketSummary(woNumber) {
  if (!secrets.serviceChannel.clientId) {
    throw new Error('ServiceChannel credentials are not configured (SC_CLIENT_ID etc.).');
  }

  try {
    const token = await getServiceChannelToken();
    const ticketRes = await axios.get(
      `${secrets.serviceChannel.baseUrl}/workorders/${woNumber}`,
      { headers: { Authorization: `Bearer ${token}` } }
    );
    const ticket = ticketRes.data;

    const notesRes = await axios.get(
      `${secrets.serviceChannel.baseUrl}/workorders/${woNumber}/notes`,
      { headers: { Authorization: `Bearer ${token}` } }
    );
    const notes = notesRes.data?.Notes || [];

    let context = `Ticket ID: ${woNumber}\n`;
    context += `Description: ${ticket.Description || 'N/A'}\n`;
    context += `Trade: ${ticket.Trade || 'N/A'} | Status: ${ticket.Status?.Primary || 'N/A'}\n`;
    context += `Notes:\n${notes.map(n => `${n.CreatedBy}: ${n.NoteData || ''}`).join('\n')}`;

    const summary = await summarizeTicketWithGrokFromContext(context, woNumber);

    return `**WO-${woNumber} Summary**\n\n${summary}`;
  } catch (err) {
    throw new Error(`Failed to fetch WO-${woNumber}: ${err.message}`);
  }
}