import { BadRequestException, Body, Controller, Delete, Get, Param, Post, Put, Query, UploadedFile, UseGuards, UseInterceptors } from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { UpdateMediaDto } from "./dto/update-media.dto";
import { MediaService } from "./media.service";
import { imageUploadOptions } from "./upload.config";

// Admin-only: the library is a management surface over ./uploads, not a
// public asset host (uploaded files themselves are still served statically
// at /uploads/* regardless of auth, same as before this module existed).
@UseGuards(JwtAuthGuard)
@Controller("media")
export class MediaController {
  constructor(private readonly media: MediaService) {}

  @Get()
  list(@Query("q") q?: string, @Query("page") page?: string, @Query("pageSize") pageSize?: string) {
    return this.media.list(q, page ? Number(page) : undefined, pageSize ? Number(pageSize) : undefined);
  }

  @Post("upload")
  @UseInterceptors(FileInterceptor("file", imageUploadOptions))
  upload(@UploadedFile() file: Express.Multer.File) {
    if (!file) throw new BadRequestException("No file uploaded.");
    return this.media.record(file);
  }

  @Put(":id")
  update(@Param("id") id: string, @Body() dto: UpdateMediaDto) {
    return this.media.update(id, dto);
  }

  @Delete(":id")
  async remove(@Param("id") id: string) {
    await this.media.remove(id);
    return { success: true };
  }
}
