import {
  Controller,
  Get,
  Param,
  Req,
  Logger,
  NotFoundException,
} from '@nestjs/common';
import { Request } from 'express';
import { GraphService } from './graph.service';
import { CrmPrismaService } from '../prisma/crm-prisma.service';

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

/**
 * GraphController — Microsoft 365 Graph-API Proxy
 *
 * Routen:
 * GET /crm/contacts/:id/emails   — E-Mails zu einem CRM-Kontakt
 * GET /crm/contacts/:id/calendar — Kalender-Termine mit einem Kontakt
 * GET /crm/contacts/:id/tasks    — Microsoft To Do Aufgaben
 */
@Controller('contacts')
export class GraphController {
  private readonly logger = new Logger(GraphController.name);

  constructor(
    private readonly graphService: GraphService,
    private readonly prisma: CrmPrismaService,
  ) {}

  /**
   * GET /api/v1/crm/contacts/:id/emails
   * E-Mails die den Kontakt betreffen aus MS Graph laden.
   */
  @Get(':id/emails')
  async getContactEmails(
    @Param('id') contactId: string,
    @Req() req: Request & { user: JwtUser },
  ) {
    const contact = await this.prisma.contact.findFirst({
      where: { id: contactId, tenantId: req.user.tenantId },
      select: { id: true, email: true },
    });

    if (!contact) {
      throw new NotFoundException('Kontakt nicht gefunden');
    }

    if (!contact.email) {
      return { success: true, data: [], meta: { reason: 'Kein E-Mail beim Kontakt hinterlegt' } };
    }

    const jwt = (req.headers.authorization ?? '').replace('Bearer ', '');
    const emails = await this.graphService.getContactEmails(
      jwt,
      req.user.sub,
      contact.email,
    );

    return { success: true, data: emails, meta: { count: emails.length } };
  }

  /**
   * GET /api/v1/crm/contacts/:id/calendar
   * Kalender-Termine mit dem Kontakt aus MS Graph laden.
   */
  @Get(':id/calendar')
  async getContactCalendar(
    @Param('id') contactId: string,
    @Req() req: Request & { user: JwtUser },
  ) {
    const contact = await this.prisma.contact.findFirst({
      where: { id: contactId, tenantId: req.user.tenantId },
      select: { id: true, email: true },
    });

    if (!contact) {
      throw new NotFoundException('Kontakt nicht gefunden');
    }

    if (!contact.email) {
      return { success: true, data: [], meta: { reason: 'Kein E-Mail beim Kontakt hinterlegt' } };
    }

    const jwt = (req.headers.authorization ?? '').replace('Bearer ', '');
    const events = await this.graphService.getContactCalendar(
      jwt,
      req.user.sub,
      contact.email,
    );

    return { success: true, data: events, meta: { count: events.length } };
  }

  /**
   * GET /api/v1/crm/contacts/:id/tasks
   * Microsoft To Do Aufgaben (nicht kontakt-spezifisch, alle Listen).
   */
  @Get(':id/tasks')
  async getContactTasks(
    @Param('id') _contactId: string,
    @Req() req: Request & { user: JwtUser },
  ) {
    const jwt = (req.headers.authorization ?? '').replace('Bearer ', '');
    const taskLists = await this.graphService.getTasks(jwt, req.user.sub);

    return {
      success: true,
      data: taskLists,
      meta: { listCount: taskLists.length },
    };
  }
}
