import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
import { FileService } from '../../services/file.service';
import { ErrorSchema } from '@d8d/shared-utils';
import { AppDataSource } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { authMiddleware } from '@d8d/auth-module/middleware';

// 删除文件路由
const deleteFileRoute = createRoute({
  method: 'delete',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '文件ID'
      })
    })
  },
  responses: {
    200: {
      description: '文件删除成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ example: true }),
            message: z.string().openapi({ example: '文件删除成功' })
          })
        }
      }
    },
    401: {
      description: '未授权访问',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '文件不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 创建路由实例
const app = new OpenAPIHono<AuthContext>().openapi(deleteFileRoute, async (c) => {
  try {
    const { id } = c.req.valid('param');

    // 创建文件服务实例
    const fileService = new FileService(AppDataSource);
    await fileService.deleteFile(id);
    return c.json({ success: true, message: '文件删除成功' }, 200);
  } catch (error) {
    const message = error instanceof Error ? error.message : '文件删除失败';
    const code = (error instanceof Error && error.message === '文件不存在') ? 404 : 500;
    return c.json({ code, message }, code);
  }
});

export default app;