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 { parseWithAwait } from '@d8d/shared-utils';
import { EnterpriseLoginSchema, EnterpriseTokenResponseSchema } from '../schemas/index';

const enterpriseLoginRoute = createRoute({
  method: 'post',
  path: '/login',
  request: {
    body: {
      content: {
        'application/json': {
          schema: EnterpriseLoginSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '企业用户登录成功',
      content: {
        'application/json': {
          schema: EnterpriseTokenResponseSchema
        }
      }
    },
    401: {
      description: '手机号或密码错误，或用户不是企业用户',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器内部错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono<AuthContext>().openapi(enterpriseLoginRoute, async (c) => {
  try {
    // 在路由处理函数内部初始化服务
    const userService = new UserService(AppDataSource);
    const authService = new AuthService(userService);

    const { phone, password } = c.req.valid('json');

    // 调用企业用户登录方法
    const result = await authService.enterpriseLogin(phone, password);

    return c.json(await parseWithAwait(EnterpriseTokenResponseSchema, result), 200);
  } catch (error) {
    // 认证相关错误返回401
    if (error instanceof Error &&
        (error.message.includes('用户不存在') ||
         error.message.includes('密码错误') ||
         error.message.includes('账户已禁用') ||
         error.message.includes('用户不是企业用户'))) {
      return c.json(
        {
          code: 401,
          message: error.message.includes('账户已禁用') ? '账户已禁用' :
                   error.message.includes('用户不是企业用户') ? '用户不是企业用户' :
                   '手机号或密码错误'
        },
        401
      );
    }

    // 其他错误重新抛出，由错误处理中间件处理
    throw error;
  }
});

export default app;