import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { AppDataSource, parseWithAwait } from '@d8d/shared-utils';
import { ErrorSchema } from '@d8d/shared-utils/schema/error'
import { talentAuthMiddleware } from '@d8d/auth-module';
import { TalentAuthContext, TalentUserBase } from '@d8d/shared-types';
import { DisabledPersonService } from '../services/disabled-person.service';
import {
  PersonalInfoResponseSchema,
  BankCardsResponseSchema,
  PhotosResponseSchema,
  PhotosQuerySchema
} from '../schemas/talent-personal-info.schema';

// 人才用户类型
type TalentUser = TalentUserBase;

/**
 * 获取人才个人信息路由
 */
const getPersonalInfoRoute = createRoute({
  method: 'get',
  path: '/personal/info',
  middleware: [talentAuthMiddleware],
  responses: {
    200: {
      description: '获取个人信息成功',
      content: {
        'application/json': { schema: PersonalInfoResponseSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '权限不足',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '用户不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取个人信息失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

/**
 * 获取银行卡信息列表路由
 */
const getBankCardsRoute = createRoute({
  method: 'get',
  path: '/personal/bank-cards',
  middleware: [talentAuthMiddleware],
  responses: {
    200: {
      description: '获取银行卡列表成功',
      content: {
        'application/json': { schema: BankCardsResponseSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '权限不足',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '用户不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取银行卡列表失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

/**
 * 获取证件照片列表路由
 */
const getPhotosRoute = createRoute({
  method: 'get',
  path: '/personal/photos',
  middleware: [talentAuthMiddleware],
  request: {
    query: PhotosQuerySchema
  },
  responses: {
    200: {
      description: '获取证件照片列表成功',
      content: {
        'application/json': { schema: PhotosResponseSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '权限不足',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '用户不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取证件照片列表失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<TalentAuthContext>()
  // 获取个人信息
  .openapi(getPersonalInfoRoute, async (c) => {
    try {
      // talentAuthMiddleware 已经验证了用户是人才用户
      const user = c.get('user') as TalentUser;
      const personId = user.personId;

      // 验证person_id是否存在
      if (!personId) {
        return c.json({
          code: 404,
          message: '用户不存在或未关联残疾人信息'
        }, 404);
      }

      const disabledPersonService = new DisabledPersonService(AppDataSource);
      const personalInfo = await disabledPersonService.getPersonalInfo(personId);

      if (!personalInfo) {
        return c.json({
          code: 404,
          message: '用户不存在'
        }, 404);
      }

      const validatedResult = await parseWithAwait(PersonalInfoResponseSchema, personalInfo);
      return c.json(validatedResult, 200);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取个人信息失败'
      }, 500);
    }
  })
  // 获取银行卡列表
  .openapi(getBankCardsRoute, async (c) => {
    try {
      // talentAuthMiddleware 已经验证了用户是人才用户
      const user = c.get('user') as TalentUser;
      const personId = user.personId;

      // 验证person_id是否存在
      if (!personId) {
        return c.json({
          code: 404,
          message: '用户不存在或未关联残疾人信息'
        }, 404);
      }

      const disabledPersonService = new DisabledPersonService(AppDataSource);
      const bankCards = await disabledPersonService.getBankCardsByPersonId(personId);

      const validatedResult = await parseWithAwait(BankCardsResponseSchema, {
        data: bankCards,
        total: bankCards.length
      });
      return c.json(validatedResult, 200);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取银行卡列表失败'
      }, 500);
    }
  })
  // 获取证件照片列表
  .openapi(getPhotosRoute, async (c) => {
    try {
      // talentAuthMiddleware 已经验证了用户是人才用户
      const user = c.get('user') as TalentUser;
      const personId = user.personId;

      // 验证person_id是否存在
      if (!personId) {
        return c.json({
          code: 404,
          message: '用户不存在或未关联残疾人信息'
        }, 404);
      }

      const query = c.req.valid('query');
      const disabledPersonService = new DisabledPersonService(AppDataSource);
      const photos = await disabledPersonService.getPhotosByPersonId(
        personId,
        query.photoType,
        query.skip,
        query.take
      );

      const validatedResult = await parseWithAwait(PhotosResponseSchema, {
        data: photos.data,
        total: photos.total
      });
      return c.json(validatedResult, 200);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取证件照片列表失败'
      }, 500);
    }
  });

export default app;
