import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
import { FileService } from '@/server/modules/files/file.service';
import { FileSchema, CreateFileDto } from '@/server/modules/files/file.schema';
import { ErrorSchema } from '@/server/utils/errorHandler';
import { AppDataSource } from '@/server/data-source';
import { AuthContext } from '@/server/types/context';
import { authMiddleware } from '@/server/middleware/auth.middleware';

// 创建文件上传策略路由
const createUploadPolicyRoute = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateFileDto }
      }
    }
  },
  responses: {
    200: {
      description: '生成文件上传策略成功',
      content: {
        'application/json': {
          schema: z.object({
            file: FileSchema,
            uploadPolicy: z.object({
              'x-amz-algorithm': z.string(),
              'x-amz-credential': z.string(),
              'x-amz-date': z.string(),
              'x-amz-security-token': z.string().optional(),
              policy: z.string(),
              'x-amz-signature': z.string(),
              host: z.string(),
              key: z.string(),
              bucket: z.string()
            })
          })
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 创建文件服务实例
const fileService = new FileService(AppDataSource);

// 创建路由实例
const app = new OpenAPIHono<AuthContext>().openapi(createUploadPolicyRoute, async (c) => {
  try {
    const data = await c.req.json();
    const user = c.get('user');
    
    // 添加用户ID到文件数据
    const fileData = {
      ...data,
      uploadUserId: user.id,
      uploadTime: new Date()
    };
    const result = await fileService.createFile(fileData);
    // 手动转换日期类型并处理可选字段
    const formattedFile = {
      ...result.file,
      description: result.file.description ?? null,
      type: result.file.type ?? null,
      size: result.file.size ?? null,
      lastUpdated: result.file.lastUpdated ? result.file.lastUpdated.toISOString() : null,
      createdAt: result.file.createdAt.toISOString(),
      uploadTime: result.file.uploadTime.toISOString()
    };
    
    const typedResult = {
      file: formattedFile,
      uploadPolicy: result.uploadPolicy
    };
    return c.json(typedResult, 200);
  } catch (error) {
    const message = error instanceof Error ? error.message : '生成上传策略失败';
    return c.json({ code: 500, message }, 500);
  }
});

export default app;