import {
  Controller,
  Get,
  Param,
  Post,
  Res,
  StreamableFile,
  HttpStatus,
  HttpCode,
} from '@nestjs/common';
import type { Response } from 'express';
import { createReadStream } from 'node:fs';
import { GlobalWordsService } from './global-words.service';

@Controller('global-words')
export class GlobalWordsController {
  constructor(private readonly globalWordsService: GlobalWordsService) {}

  @Get()
  async getWords() {
    return this.globalWordsService.listWords();
  }

  @Post('prefetch')
  @HttpCode(HttpStatus.ACCEPTED)
  async prefetchAll() {
    this.globalWordsService.prefetchAll();
    return { status: 'scheduled' };
  }

  @Post(':slug/generate')
  async generateForWord(@Param('slug') slug: string) {
    await this.globalWordsService.ensureImage(slug);
    return { slug, status: 'ready' };
  }

  @Get(':slug/image')
  async getImage(@Param('slug') slug: string, @Res({ passthrough: true }) res: Response) {
    const asset = await this.globalWordsService.ensureImage(slug);
    res.setHeader('Content-Type', asset.mimeType);
    const file = createReadStream(asset.path);
    return new StreamableFile(file);
  }
}
