import { Controller, Get, Req, Logger } from '@nestjs/common';
import { Request } from 'express';
import { GraphService } from './graph.service';

interface JwtUser {
  sub: string;
  email: string;
  tenantId: string;
}

/**
 * Office365Controller — Globale Microsoft 365 Übersicht
 *
 * Zeigt alle M365-Daten des eingeloggten Users (ohne Kontakt-Filter).
 *
 * Routen:
 * GET /crm/office365/emails    — Alle E-Mails (Posteingang)
 * GET /crm/office365/calendar  — Alle Kalendertermine (nächste 30 Tage)
 * GET /crm/office365/contacts  — Alle Outlook-Kontakte
 * GET /crm/office365/tasks     — Alle Aufgaben (Microsoft To Do)
 */
@Controller('office365')
export class Office365Controller {
  private readonly logger = new Logger(Office365Controller.name);

  constructor(private readonly graphService: GraphService) {}

  @Get('emails')
  async getEmails(@Req() req: Request & { user: JwtUser }) {
    const jwt = (req.headers.authorization ?? '').replace('Bearer ', '');
    const emails = await this.graphService.getAllEmails(jwt, req.user.sub);
    return { success: true, data: emails, meta: { count: emails.length } };
  }

  @Get('calendar')
  async getCalendar(@Req() req: Request & { user: JwtUser }) {
    const jwt = (req.headers.authorization ?? '').replace('Bearer ', '');
    const events = await this.graphService.getAllCalendarEvents(jwt, req.user.sub);
    return { success: true, data: events, meta: { count: events.length } };
  }

  @Get('contacts')
  async getContacts(@Req() req: Request & { user: JwtUser }) {
    const jwt = (req.headers.authorization ?? '').replace('Bearer ', '');
    const contacts = await this.graphService.getAllOutlookContacts(jwt, req.user.sub);
    return { success: true, data: contacts, meta: { count: contacts.length } };
  }

  @Get('tasks')
  async getTasks(@Req() req: Request & { user: JwtUser }) {
    const jwt = (req.headers.authorization ?? '').replace('Bearer ', '');
    const taskLists = await this.graphService.getTasks(jwt, req.user.sub);
    const totalTasks = taskLists.reduce((sum, l) => sum + l.tasks.length, 0);
    return {
      success: true,
      data: taskLists,
      meta: { listCount: taskLists.length, taskCount: totalTasks },
    };
  }
}
