import {
  Controller,
  Get,
  Param,
  Res,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import type { Response } from 'express';
import { PostService } from './post.service';
import { IsString, Matches } from 'class-validator';
import { validateOrReject } from 'class-validator';

class SlugDto {
  @IsString()
  @Matches(/^[A-Za-z0-9-]+$/, {
    message: 'Slug can only contain letters, numbers, and dashes',
  })
  slug: string;
}

@Controller('blog') // No /api prefix, legacy route
export class LegacyBlogController {
  constructor(private readonly postService: PostService) {}

  @Get(':slug')
  async redirectLegacy(@Param('slug') slug: string, @Res() res: Response) {
    console.log('Legacy slug received:', slug);

    // OLD QR: page_id=xxxx
    if (slug.startsWith('page_id=')) {
      const pageId = slug.split('=')[1];
      if (!pageId) throw new BadRequestException('Invalid page_id format');

      const post = await this.postService.getPostByPageId(pageId);
      if (!post) throw new NotFoundException('Certificate not found');

      console.log('Redirecting legacy page_id to:', post.guid);
      return res.redirect(post.guid);
    }

    // NEW slug format (optional)
    const dto = new SlugDto();
    dto.slug = slug;
    try {
      await validateOrReject(dto);
    } catch {
      throw new BadRequestException('Invalid slug format');
    }

    let post = await this.postService.getPostBySlug(slug, 'intl');
    if (!post) post = await this.postService.getPostBySlug(slug, 'syst');

    if (!post) throw new NotFoundException('Certificate not found');

    console.log('Redirecting legacy slug to:', post.guid);
    return res.redirect(post.guid);
  }
}
