import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { AuthService } from '../../services/index';
import { UserService } from '@d8d/core-module/user-module';
import { ErrorSchema } from '@d8d/shared-utils';
import { AppDataSource } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { TalentLogoutResponseSchema } from '../../schemas/index';
import { talentAuthMiddleware } from '../../middleware/index';

const talentLogoutRoute = createRoute({
  method: 'post',
  path: '/logout',
  security: [
    {
      Bearer: []
    }
  ],
  middleware: talentAuthMiddleware,
  responses: {
    200: {
      description: '登出成功',
      content: {
        'application/json': {
          schema: TalentLogoutResponseSchema
        }
      }
    },
    401: {
      description: '未授权或token无效',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器内部错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono<AuthContext>().openapi(talentLogoutRoute, async (c) => {
  try {
    const token = c.get('token');
    if (!token) {
      return c.json({ code: 401, message: '未授权' }, 401);
    }

    const userService = new UserService(AppDataSource);
    const authService = new AuthService(userService);

    await authService.logout(token);

    return c.json({ message: '登出成功' }, 200);
  } catch (error) {
    return c.json(
      {
        code: 500,
        message: error instanceof Error ? error.message : '登出失败'
      },
      500
    );
  }
});

export default app;
