import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Param,
  Body,
  UseGuards,
  ParseIntPipe,
  UseInterceptors,
  UploadedFile,
  BadRequestException,
  Query,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { IsOptional, IsString, MaxLength } from 'class-validator';
import * as path from 'path';
import * as fs from 'fs';
import * as crypto from 'crypto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { Permissions } from '../auth/permissions.decorator';
import { PermissionsGuard } from '../auth/guards/permissions.guard';
import { CurrentUser, AuthenticatedUser } from '../common/decorators/current-user.decorator';
import { MediaService } from './media.service';

const uploadDir = path.join(process.cwd(), 'uploads', 'media');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

const ALLOWED_MIME_TYPES = [
  'image/jpeg',
  'image/png',
  'image/gif',
  'image/webp',
  'image/svg+xml',
  'video/mp4',
  'video/webm',
  'audio/mpeg',
  'audio/wav',
  'application/pdf',
];

const MAX_FILE_SIZE = Number(process.env.MAX_UPLOAD_BYTES || 100 * 1024 * 1024);

const storage = diskStorage({
  destination: (_req, _file, cb) => cb(null, uploadDir),
  filename: (_req, file, cb) => {
    // Never trust the client filename on disk - it is kept only as metadata.
    const ext = path.extname(file.originalname).toLowerCase().slice(0, 10);
    cb(null, `${Date.now()}-${crypto.randomBytes(8).toString('hex')}${ext}`);
  },
});

const fileFilter = (_req: any, file: Express.Multer.File, cb: any) => {
  if (ALLOWED_MIME_TYPES.includes(file.mimetype)) return cb(null, true);
  cb(new BadRequestException(`Unsupported file type: ${file.mimetype}`), false);
};

export class UpdateMediaDto {
  @IsOptional()
  @IsString()
  @MaxLength(512)
  fileName?: string;

  @IsOptional()
  @IsString()
  @MaxLength(512)
  caption?: string;

  @IsOptional()
  @IsString()
  @MaxLength(512)
  altText?: string;
}

@Controller('api/v1/admin/media')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class MediaController {
  constructor(private readonly mediaService: MediaService) {}

  @Post()
  @Permissions('media.upload')
  @UseInterceptors(
    FileInterceptor('file', { storage, fileFilter, limits: { fileSize: MAX_FILE_SIZE } }),
  )
  async upload(
    @UploadedFile() file: Express.Multer.File,
    @Body() body: UpdateMediaDto,
    @CurrentUser() user: AuthenticatedUser,
  ) {
    if (!file) throw new BadRequestException('No file provided');

    const media = await this.mediaService.create({
      fileName: file.originalname,
      fileType: MediaService.classify(file.mimetype),
      mimeType: file.mimetype,
      fileSize: file.size,
      storagePath: `/uploads/media/${file.filename}`,
      caption: body?.caption,
      altText: body?.altText,
      status: 'ACTIVE',
      createdBy: user?.id,
    });

    return { success: true, message: 'File uploaded successfully', data: media };
  }

  @Get()
  @Permissions('media.view')
  async findAll(
    @Query('search') search?: string,
    @Query('fileType') fileType?: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    const { items, meta } = await this.mediaService.findAll({
      search,
      fileType,
      page: page ? Number(page) : undefined,
      limit: limit ? Number(limit) : undefined,
    });
    return { success: true, message: 'Success', data: items, meta };
  }

  @Get(':id')
  @Permissions('media.view')
  async findById(@Param('id', ParseIntPipe) id: number) {
    const media = await this.mediaService.findById(id);
    if (!media) return { success: false, message: 'Media not found' };
    return { success: true, message: 'Success', data: media };
  }

  @Put(':id')
  @Permissions('media.update')
  async update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateMediaDto) {
    const data = await this.mediaService.update(id, dto);
    return { success: true, message: 'Media updated', data };
  }

  @Delete(':id')
  @Permissions('media.delete')
  async delete(@Param('id', ParseIntPipe) id: number) {
    const success = await this.mediaService.delete(id);
    return { success, message: success ? 'Media deleted' : 'Media not found' };
  }
}
