import {
  BadRequestException,
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { MediaService } from "../media/media.service";
import { imageUploadOptions } from "../media/upload.config";
import { ContentService } from "./content.service";
import { PublishService } from "./publish.service";
import { CreatePageDto } from "./dto/create-page.dto";
import { UpdateBlockDto } from "./dto/update-block.dto";
import { UpdateSeoDto } from "./dto/update-seo.dto";

@Controller("content")
export class ContentController {
  constructor(
    private readonly content: ContentService,
    private readonly publish: PublishService,
    private readonly media: MediaService,
  ) {}

  // Public read endpoints — this is the site's own published copy, no
  // different from what's already visible in the page source. Consumed at
  // build time by the frontend's server components (see
  // frontend/src/lib/content-fetch.ts).
  @Get("pages")
  listPages() {
    return this.content.listPages();
  }

  @Get("pages/:slug")
  getPage(@Param("slug") slug: string) {
    return this.content.getPageBySlug(slug);
  }

  @UseGuards(JwtAuthGuard)
  @Post("pages")
  createPage(@Body() dto: CreatePageDto) {
    return this.content.createPage(dto);
  }

  @UseGuards(JwtAuthGuard)
  @Delete("pages/:slug")
  async deletePage(@Param("slug") slug: string) {
    await this.content.deletePage(slug);
    return { success: true };
  }

  @UseGuards(JwtAuthGuard)
  @Put("blocks/:id")
  updateBlock(@Param("id") id: string, @Body() dto: UpdateBlockDto) {
    return this.content.updateBlock(id, dto);
  }

  @UseGuards(JwtAuthGuard)
  @Put("pages/:slug/seo")
  updateSeo(@Param("slug") slug: string, @Body() dto: UpdateSeoDto) {
    return this.content.upsertSeoFields(slug, dto);
  }

  @UseGuards(JwtAuthGuard)
  @Post("upload")
  @UseInterceptors(FileInterceptor("file", imageUploadOptions))
  async upload(@UploadedFile() file: Express.Multer.File) {
    if (!file) throw new BadRequestException("No file uploaded.");
    const asset = await this.media.record(file);
    return { url: asset.url };
  }

  @UseGuards(JwtAuthGuard)
  @Post("publish")
  triggerPublish() {
    return this.publish.trigger();
  }

  @UseGuards(JwtAuthGuard)
  @Get("publish/status")
  publishStatus() {
    return this.publish.getStatus();
  }
}
