import {
  Controller,
  All,
  Req,
  Res,
  Get,
  Post,
  Patch,
  Param,
  Delete,
  Head,
  Options,
  NotFoundException,
  HttpException,
  HttpStatus,
  Body,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { TusService } from './tus.service';
import { ShareCodeService } from './share-code.service';
import { ResourceService } from '@server/models/resource/resource.service';

interface ResourceMeta {
  filename: string;
  filetype: string;
  filesize: string;
}

@Controller('upload')
export class UploadController {
  constructor(
    private readonly tusService: TusService,
    private readonly shareCodeService: ShareCodeService,
    private readonly resourceService: ResourceService,
  ) {}
  // @Post()
  // async handlePost(@Req() req: Request, @Res() res: Response) {
  //     return this.tusService.handleTus(req, res);
  // }

  @Options()
  async handleOptions(@Req() req: Request, @Res() res: Response) {
    return this.tusService.handleTus(req, res);
  }

  @Head()
  async handleHead(@Req() req: Request, @Res() res: Response) {
    return this.tusService.handleTus(req, res);
  }

  @Post()
  async handlePost(@Req() req: Request, @Res() res: Response) {
    return this.tusService.handleTus(req, res);
  }
  @Get('share/:code')
  async validateShareCode(@Param('code') code: string) {
    console.log('收到验证分享码请求，code:', code);
    
    const shareCode = await this.shareCodeService.validateAndUseCode(code);
    console.log('验证分享码结果:', shareCode);
    
    if (!shareCode) {
        throw new NotFoundException('分享码无效或已过期');
    }

    // 获取文件信息
    const resource = await this.resourceService.findUnique({
        where: { fileId: shareCode.fileId },
    });
    console.log('获取到的资源信息:', resource);
    const {filename} = resource.meta as any as ResourceMeta
    if (!resource) {
        throw new NotFoundException('文件不存在');
    }

    // 直接返回正确的数据结构
    const response = {
        fileId: shareCode.fileId,
        fileName:filename || 'downloaded_file',
        code: shareCode.code,
        expiresAt: shareCode.expiresAt
    };

    console.log('返回给前端的数据:', response);  // 添加日志
    return response;
  }

  @Get('share/info/:code')
  async getShareCodeInfo(@Param('code') code: string) {
    const info = await this.shareCodeService.getShareCodeInfo(code);
    if (!info) {
      throw new NotFoundException('分享码不存在');
    }
    return info;
  }

  @Get('share/history/:fileId')
  async getFileShareHistory(@Param('fileId') fileId: string) {
    return this.shareCodeService.getFileShareHistory(fileId);
  }
  @Get('/*')
  async handleGet(@Req() req: Request, @Res() res: Response) {
    return this.tusService.handleTus(req, res);
  }

  @Patch('/*')
  async handlePatch(@Req() req: Request, @Res() res: Response) {
    return this.tusService.handleTus(req, res);
  }

  // Keeping the catch-all method as a fallback
  @All()
  async handleUpload(@Req() req: Request, @Res() res: Response) {
    return this.tusService.handleTus(req, res);
  }
  @Post('share/:fileId(*)')
  async generateShareCode(@Param('fileId') fileId: string) {
    try {
      console.log('收到生成分享码请求，fileId:', fileId);
      const result = await this.shareCodeService.generateShareCode(fileId);
      console.log('生成分享码结果:', result);
      return result;
    } catch (error) {
      console.error('生成分享码错误:', error);
      throw new HttpException(
        {
          message: (error as Error).message || '生成分享码失败',
          error: 'SHARE_CODE_GENERATION_FAILED'
        },
        HttpStatus.INTERNAL_SERVER_ERROR
      );
    }
  }

  @Post('filename')
  async saveFileName(@Body() data: { fileId: string; fileName: string }) {
    try {
      console.log('收到保存文件名请求:', data);
      
      // 检查参数
      if (!data.fileId || !data.fileName) {
        throw new HttpException(
          { message: '缺少必要参数' },
          HttpStatus.BAD_REQUEST
        );
      }
      // 保存文件名
      await this.resourceService.saveFileName(data.fileId, data.fileName);
      console.log('文件名保存成功:', data.fileName, '对应文件ID:', data.fileId);
      
      return { success: true };
    } catch (error) {
      console.error('保存文件名失败:', error);
      throw new HttpException(
        {
          message: '保存文件名失败',
          error: (error instanceof Error) ? error.message : String(error)
        },
        HttpStatus.INTERNAL_SERVER_ERROR
      );
    }
  }

  @Get('download/:fileId')
  async downloadFile(@Param('fileId') fileId: string, @Res() res: Response) {
    try {
      // 获取文件信息
      const resource = await this.resourceService.findUnique({
        where: { fileId },
      });
      
      if (!resource) {
        throw new NotFoundException('文件不存在');
      }
      
      // 获取原始文件名
      const fileName = await this.resourceService.getFileName(fileId) || 'downloaded-file';
      
      // 设置响应头，包含原始文件名
      res.setHeader(
        'Content-Disposition', 
        `attachment; filename="${encodeURIComponent(fileName)}"`
      );
      
      // 其他下载逻辑...
      
    } catch (error) {
      // 错误处理...
    }
  }

}
