import {
  Controller,
  Get,
  Param,
  Query,
  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';

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

@Controller(['blog', 'api/blog']) // Handles both /blog/* and /api/blog/*
export class BlogController {
  constructor(private readonly postService: PostService) {}

  // ------------------------------
  // 1️⃣ Legacy QR format (query param)
  // Example: /api/blog/?page_id=14926
  // ------------------------------
  // ... inside BlogController class

@Get()
async redirectByQuery(@Query('page_id') pageId: string, @Res() res: Response) {
  console.log('🟢 Received legacy query param page_id:', pageId);
  if (!pageId) {
    console.log('⚠️ No page_id provided in query');
    return res.status(404).send('Invalid request');
  }

  const post = await this.postService.getPostByPageId(pageId);
  if (!post) {
    console.log('⚠️ No post found for page_id:', pageId);
    throw new NotFoundException('Certificate not found');
  }

  const fileUrl = await this.postService.getFileUrlForPost(post);
  console.log(`🔵 Redirecting legacy page_id=${pageId} to file URL: ${fileUrl}`);
  return res.redirect(fileUrl);
}

@Get(':slug')
async redirectByPath(@Param('slug') slug: string, @Res() res: Response) {
  console.log('🟢 Received slug/path:', slug);

  // legacy page_id in path
  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');

    const fileUrl = await this.postService.getFileUrlForPost(post);
    console.log(`🔵 Redirecting legacy page_id=${pageId} to file URL: ${fileUrl}`);
    return res.redirect(fileUrl);
  }

  // new slug format
  const dto = new SlugDto();
  dto.slug = slug;
  try {
    await validateOrReject(dto);
  } catch {
    console.log('⚠️ Slug validation failed for:', slug);
    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');

  const fileUrl = await this.postService.getFileUrlForPost(post);
  console.log(`🔵 Redirecting slug=${slug} to file URL: ${fileUrl}`);
  return res.redirect(fileUrl);
}


  // ------------------------------
  // 2️⃣ Path-based: /blog/:slug or /blog/page_id=14926
  // ------------------------------
  // @Get(':slug')
  // async redirectByPath(@Param('slug') slug: string, @Res() res: Response) {
  //   console.log('🟢 Received slug/path:', slug);

  //   // --- Legacy page_id inside path ---
  //   if (slug.startsWith('page_id=')) {
  //     const pageId = slug.split('=')[1];
  //     console.log('🟡 Detected legacy page_id in path:', pageId);

  //     if (!pageId) throw new BadRequestException('Invalid page_id format');

  //     const post = await this.postService.getPostByPageId(pageId);
  //     console.log('🟢 Page ID query result:', post);

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

  //     console.log(`🔵 Redirecting legacy page_id=${pageId} to: ${post.guid}`);
  //     return res.redirect(post.guid);
  //   }

  //   // --- New slug format validation ---
  //   const dto = new SlugDto();
  //   dto.slug = slug;
  //   try {
  //     await validateOrReject(dto);
  //   } catch {
  //     console.log('⚠️ Slug validation failed for:', slug);
  //     throw new BadRequestException('Invalid slug format');
  //   }

  //   // --- Search in WordPress DB ---
  //   let post = await this.postService.getPostBySlug(slug, 'intl');
  //   if (!post) post = await this.postService.getPostBySlug(slug, 'syst');

  //   console.log('🟢 Slug query result:', post);

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

  //   console.log(`🔵 Redirecting slug=${slug} to: ${post.guid}`);
  //   return res.redirect(post.guid);
  // }
}
