import {
  Controller,
  Post,
  Param,
  Get,
  UseGuards,
  Res,
  NotFoundException,
} from "@nestjs/common";
import { ApiBearerAuth, ApiTags } from "@nestjs/swagger";
import type { Response } from "express";
import * as fs from "fs";

import { SocialPosterService } from "./social-poster.service";
import { Roles } from "../../common/decorators";
import { RolesGuard } from "../auth/guards/auth.guards";

@ApiTags("Social Poster")
@Controller("social-poster")
export class SocialPosterController {
  constructor(private readonly socialPosterService: SocialPosterService) {}

  /** Public health endpoint — config + last-run snapshot. Safe to expose. */
  @Get("health")
  health() {
    return this.socialPosterService.getHealthStatus();
  }

  @ApiBearerAuth()
  @UseGuards(RolesGuard)
  @Roles("superadmin")
  @Get("preview/:matchId")
  async previewCard(@Param("matchId") matchId: string) {
    return this.socialPosterService.renderPreview(matchId);
  }

  /**
   * Render the prediction card for a match and stream the raw JPEG back —
   * the fastest way to QA the visual without opening the JSON or a viewer.
   */
  @ApiBearerAuth()
  @UseGuards(RolesGuard)
  @Roles("superadmin")
  @Get("preview-png/:matchId")
  async previewPng(
    @Param("matchId") matchId: string,
    @Res() res: Response,
  ): Promise<void> {
    const { imagePath } = await this.socialPosterService.renderPreview(matchId);
    if (!fs.existsSync(imagePath)) {
      throw new NotFoundException("Image not rendered");
    }
    res.setHeader("Content-Type", "image/jpeg");
    res.setHeader(
      "Cache-Control",
      "public, max-age=300, stale-while-revalidate=60",
    );
    fs.createReadStream(imagePath).pipe(res);
  }

  @ApiBearerAuth()
  @UseGuards(RolesGuard)
  @Roles("superadmin")
  @Post("post/:matchId")
  async postMatch(@Param("matchId") matchId: string) {
    return this.socialPosterService.manualPost(matchId);
  }

  /**
   * Force a cron-style sweep right now — useful right after pushing config
   * changes, instead of waiting up to 10 minutes for the next scheduled run.
   */
  @ApiBearerAuth()
  @UseGuards(RolesGuard)
  @Roles("superadmin")
  @Post("run-now")
  async runNow() {
    await this.socialPosterService.checkAndPostUpcomingMatches();
    return this.socialPosterService.getHealthStatus();
  }
}
