import { http, HttpResponse } from 'msw'
import type { User } from '@/services/auth'
import type { ApiResponse } from '@/types/api'
import { API_STATUS } from '@/types/api'
import { Gender } from '@/types/user'
import { AiUserInfoOutput, ContentStatus } from '@/services/create'
import { LikedStatus, LockStatus } from '@/services/user'

let cpUserInfo = false

// Mock 数据
const mockUsers: User[] = [
  {
    userId: 1,
    nickname: '张三',
    headImage: 'https://global-oss.epal.gg/data/cover/2230384/17031872250492121.jpeg',
    sex: Gender.MALE,
    birthday: new Date('1990-01-01').getTime(),
    cpUserInfo: cpUserInfo,
  },
  {
    userId: 2,
    nickname: '李四',
    headImage: undefined,
    sex: Gender.OTHER,
    birthday: new Date('1992-05-15').getTime(),
    cpUserInfo: false,
  },
]

// 模拟的 token
const MOCK_TOKEN = 'mock-jwt-token-12345'

// 验证设备ID的辅助函数
function validateDeviceId(request: Request): { deviceId: string | null; isValid: boolean } {
  const deviceId = request.headers.get('AUTH_DID')

  if (!deviceId) {
    console.warn('⚠️ 请求缺少设备ID (AUTH_DID)')
    return { deviceId: null, isValid: false }
  }

  // 简单验证设备ID格式
  if (!deviceId.startsWith('did_')) {
    console.warn('⚠️ 设备ID格式不正确:', deviceId)
    return { deviceId, isValid: false }
  }

  console.log('✅ 设备ID验证通过:', deviceId)
  return { deviceId, isValid: true }
}

// 创建成功响应的辅助函数
function createSuccessResponse<T>(content: T): ApiResponse<T> {
  return {
    content,
    status: API_STATUS.OK,
    errorCode: '',
    errorMsg: '',
    traceId: `trace-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
  }
}

// 创建错误响应的辅助函数
function createErrorResponse(errorCode: string, errorMsg: string): ApiResponse<null> {
  return {
    content: null,
    status: 'ERROR',
    errorCode,
    errorMsg,
    traceId: `trace-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
  }
}

export const handlers = [
  // 认证服务 Mock - 第三方登录（Discord、Google、Apple）
  http.post('*/web/third/login', async ({ request }) => {
    console.log('🔐 第三方登录请求')

    // 验证设备ID
    const { deviceId, isValid } = validateDeviceId(request)
    if (!isValid) {
      return HttpResponse.json(createErrorResponse('DEVICE_ID_REQUIRED', '设备ID无效或缺失'))
    }
    const body = (await request.json()) as any
    const { thirdType, thirdToken, appClient } = body
    console.log(`📱 第三方登录类型: ${thirdType}, 客户端: ${appClient}`)
    const loginResponse = {
      token: MOCK_TOKEN,
    }

    console.log(`✅ ${thirdType}登录成功，设备ID: ${deviceId}`)
    return HttpResponse.json(createSuccessResponse(loginResponse))
  }),

  http.get('*/web/user/base-info', async ({ request }) => {
    console.log('👤 获取用户信息')

    const authToken = request.headers.get('AUTH_TK')
    const { deviceId, isValid } = validateDeviceId(request)

    if (!isValid) {
      return HttpResponse.json(createErrorResponse('DEVICE_ID_REQUIRED', '设备ID无效或缺失'))
    }

    if (!authToken || authToken !== MOCK_TOKEN) {
      return HttpResponse.json(createErrorResponse('AUTH_TOKEN_INVALID', '认证令牌无效或已过期'))
    }

    return HttpResponse.json(createSuccessResponse(mockUsers[0]))
  }),

  http.post('*/web/user/complete-user-info', async ({ request }) => {
    console.log('👤 完善用户信息')
    cpUserInfo = true
    const authToken = request.headers.get('AUTH_TK')
    const { deviceId, isValid } = validateDeviceId(request)

    if (!isValid) {
      return HttpResponse.json(createErrorResponse('DEVICE_ID_REQUIRED', '设备ID无效或缺失'))
    }

    if (!authToken || authToken !== MOCK_TOKEN) {
      return HttpResponse.json(createErrorResponse('AUTH_TOKEN_INVALID', '认证令牌无效或已过期'))
    }

    const body = (await request.json()) as any
    const { nickname, sex, birthday } = body

    return HttpResponse.json(createSuccessResponse({ success: true }))
  }),

  http.post('*/web/user/update-user-info', async ({ request }) => {
    console.log('👤 更新用户信息')
    const authToken = request.headers.get('AUTH_TK')
    const { deviceId, isValid } = validateDeviceId(request)

    if (!isValid) {
      return HttpResponse.json(createErrorResponse('DEVICE_ID_REQUIRED', '设备ID无效或缺失'))
    }

    if (!authToken || authToken !== MOCK_TOKEN) {
      return HttpResponse.json(createErrorResponse('AUTH_TOKEN_INVALID', '认证令牌无效或已过期'))
    }

    const body = (await request.json()) as any
    const { nickname, birthday, userId } = body
    console.log(nickname, birthday, userId)

    mockUsers[0].nickname = nickname
    mockUsers[0].birthday = birthday
    mockUsers[0].userId = userId

    return HttpResponse.json(createSuccessResponse({ success: true }))
  }),

  http.post('*/web/user/logout', async ({ request }) => {
    console.log('🚪 退出登录')

    const authToken = request.headers.get('AUTH_TK')
    const { deviceId, isValid } = validateDeviceId(request)

    if (!isValid) {
      return HttpResponse.json(createErrorResponse('DEVICE_ID_REQUIRED', '设备ID无效或缺失'))
    }

    if (!authToken || authToken !== MOCK_TOKEN) {
      return HttpResponse.json(createErrorResponse('AUTH_TOKEN_INVALID', '认证令牌无效或已过期'))
    }

    return HttpResponse.json(createSuccessResponse({ success: true }))
  }),

  http.post('*/web/user/del', async ({ request }) => {
    console.log('👤 删除用户')

    const authToken = request.headers.get('AUTH_TK')
    const { deviceId, isValid } = validateDeviceId(request)

    if (!isValid) {
      return HttpResponse.json(createErrorResponse('DEVICE_ID_REQUIRED', '设备ID无效或缺失'))
    }

    if (!authToken || authToken !== MOCK_TOKEN) {
      return HttpResponse.json(createErrorResponse('AUTH_TOKEN_INVALID', '认证令牌无效或已过期'))
    }

    return HttpResponse.json(createSuccessResponse({ success: true }))
  }),

  http.post('*/web/get-ai-dict', async ({ request }) => {
    console.log('👤 获取AI字典信息')
    return HttpResponse.json(
      createSuccessResponse({
        roleDictList: [
          {
            code: '1',
            name: '原创',
            childDictList: [
              {
                code: '1-1',
                name: '原创',
              },
            ],
          },
          {
            code: '2',
            name: '同人',
            childDictList: [
              {
                code: '2-1',
                name: '动漫',
              },
              {
                code: '2-2',
                name: '游戏',
              },
              {
                code: '2-3',
                name: '影视',
              },
            ],
          },
        ],
        characterDictList: [
          {
            code: '1',
            name: '性格1',
          },
          {
            code: '2',
            name: '性格2',
          },
        ],
        tagDictList: [
          {
            code: '1',
            name: '标签1',
          },
          {
            code: '2',
            name: '标签2',
          },
        ],
        imageStyleDictList: [
          {
            id: 1,
            name: '风格1',
            url: 'https://picsum.photos/108/108?random=1',
          },
          {
            id: 2,
            name: '风格2',
            url: 'https://picsum.photos/108/108?random=2',
          },
          {
            id: 3,
            name: '风格3',
            url: 'https://picsum.photos/108/108?random=3',
          },
          {
            id: 4,
            name: '风格4',
            url: 'https://picsum.photos/108/108?random=4',
          },
          {
            id: 5,
            name: '风格5',
            url: 'https://picsum.photos/108/108?random=5',
          },
          {
            id: 6,
            name: '风格6',
            url: 'https://picsum.photos/108/108?random=6',
          },
          {
            id: 7,
            name: '风格7',
            url: 'https://picsum.photos/108/108?random=7',
          },
          {
            id: 8,
            name: '风格8',
            url: 'https://picsum.photos/108/108?random=8',
          },
          {
            id: 9,
            name: '风格9',
            url: 'https://picsum.photos/108/108?random=9',
          },
        ],
        timbreDictList: [
          {
            id: '1',
            name: '男音色1',
            description: '男音色1描述',
            type: 1,
            url: 'https://sound-oss.epal.gg/data/sound/2781558/17489556667515289.mp3',
          },
          {
            id: '2',
            name: '男音色2',
            description: '男音色2描述',
            type: 1,
            url: 'https://sound-oss.epal.gg/data/sound/2781558/17489556667515289.mp3',
          },
          {
            id: '3',
            name: '男音色3',
            description: '男音色3描述',
            type: 1,
            url: 'https://sound-oss.epal.gg/data/sound/2781558/17489556667515289.mp3',
          },
          {
            id: '4',
            name: '男音色4',
            description: '男音色4描述',
            type: 1,
            url: 'https://sound-oss.epal.gg/data/sound/2781558/17489556667515289.mp3',
          },
          {
            id: '5',
            name: '女音色1',
            description: '女音色1描述',
            type: 2,
            url: 'https://sound-oss.epal.gg/data/sound/2781558/17489556667515289.mp3',
          },
          {
            id: '6',
            name: '女音色2',
            description: '女音色2描述',
            type: 2,
            url: 'https://sound-oss.epal.gg/data/sound/2781558/17489556667515289.mp3',
          },
          {
            id: '7',
            name: '女音色3',
            description: '女音色3描述',
            type: 2,
            url: 'https://sound-oss.epal.gg/data/sound/2781558/17489556667515289.mp3',
          },
          {
            id: '8',
            name: '女音色4',
            description: '女音色4描述',
            type: 2,
            url: 'https://sound-oss.epal.gg/data/sound/2781558/17489556667515289.mp3',
          },
        ],
      })
    )
  }),

  http.post('*/web/gen/user-content', async ({ request }) => {
    console.log('👤 使用AI生成内容')
    return HttpResponse.json(
      createSuccessResponse({
        appearance: 'appearance: AI生成内容',
        dialogue: 'dialogue: AI生成内容',
        figure: 'figure: AI生成内容',
        introduction: 'introduction: AI生成内容',
        profile: 'profile: AI生成内容',
        prologue: 'prologue: AI生成内容',
      })
    )
  }),

  http.post('*/web/gen/image-ct', async ({ request }) => {
    console.log('👤 生成图片')
    return HttpResponse.json(
      createSuccessResponse({
        batchNo: Date.now().toString(),
      })
    )
  }),

  http.post('*/web/gen/image-pl', async ({ request }) => {
    console.log('👤 轮询查询图片生成结果')
    return HttpResponse.json(
      createSuccessResponse([
        {
          imageUrl: 'https://picsum.photos/400/600?random=1',
          status: ContentStatus.Completed,
        },
        {
          imageUrl: 'https://picsum.photos/400/600?random=2',
          status: ContentStatus.Completed,
        },
        {
          imageUrl: 'https://picsum.photos/108/108?random=2',
          status: ContentStatus.Pending,
        },
        {
          imageUrl: 'https://picsum.photos/108/108?random=4',
          status: ContentStatus.Pending,
        },
        {
          imageUrl: 'https://picsum.photos/108/108?random=5',
          status: ContentStatus.Pending,
        },
        {
          imageUrl: '',
          status: ContentStatus.Pending,
        },
      ])
    )
  }),

  http.post('*/web/ai-user/create-edit', async ({ request }) => {
    console.log('👤 创建或编辑AI')
    return HttpResponse.json(createSuccessResponse({ success: true }))
  }),

  http.post('*/web/ai-user-search/base-info', async ({ request }) => {
    console.log('👤 获取AI用户基础信息')
    return HttpResponse.json(
      createSuccessResponse({
        age: 20,
        aiId: 1,
        userId: 1,
        characterName: '性格1',
        headImg: 'https://hhb.crushlevel.ai/dev/role/17543853962426729.jpg',
        homeImageUrl: 'https://hhb.crushlevel.ai/dev/role/17543853962426729.jpg',
        introduction: '简介简介简介简介简介简介',
        nickname: '张三',
        roleName: '角色1',
        sex: 1,
        tagName: '标签1',
      })
    )
  }),

  http.post('*/web/ai-user/stat', async ({ request }) => {
    console.log('👤 获取AI用户统计信息')
    return HttpResponse.json(
      createSuccessResponse({
        chatNum: 0,
        coinNum: 10000,
        conversationNum: 2000,
        likedNum: 100,
      })
    )
  }),

  http.post('*/web/ai-user-gift/list', async ({ request }) => {
    console.log('👤 获取AI用户礼物信息')
    return HttpResponse.json(
      createSuccessResponse({
        datas: new Array(30).fill(0).map((_, index) => ({
          id: index + 1,
          name: `礼物${index + 1}`,
          icon: `https://picsum.photos/108/108?random=${index + 1}`,
          getNum: index + 1,
        })),
        pn: 1,
        ps: 30,
        tc: 30,
      })
    )
  }),

  // 获取AI用户相册列表
  http.post('*/web/ai-user/album-list', async ({ request }) => {
    console.log('📸 获取AI用户相册列表')

    const body = (await request.json()) as { aiId: number; page: { pn: number; ps: number } }
    const { page } = body
    const { pn = 1, ps = 20 } = page

    // 生成模拟相册数据
    const albumItems = new Array(Math.min(ps, 15)).fill(0).map((_, index) => {
      const id = (pn - 1) * ps + index + 1
      const tagTypes = ['default', 'private', 'public', 'premium'] as const
      const tagType = tagTypes[index % tagTypes.length]

      return {
        albumId: id,
        width: '108',
        height: '108',
        img1: `https://picsum.photos/108/108?random=${index + 1}`,
        img3: `https://picsum.photos/108/108?random=${index + 1}`,
        imgOrder: index + 1,
        imgUrl: `https://picsum.photos/108/108?random=${index + 1}`,
        isDefault: index === 0,
        likedCount: Math.floor(Math.random() * 100),
        likedStatus: Math.random() > 0.7 ? LikedStatus.Liked : LikedStatus.Canceled,
        lockStatus: Math.random() > 0.7 ? LockStatus.Lock : LockStatus.Unlock,
        unlockPrice: Math.floor(Math.random() * 50) + 10,
      }
    })

    return HttpResponse.json(
      createSuccessResponse({
        datas: albumItems,
        pn,
        ps,
        tc: 100, // 总共45张图片
      })
    )
  }),

  // 点赞/取消点赞相册图片
  http.post('*/web/album/like_or_cancel', async ({ request }) => {
    console.log('❤️ 点赞/取消点赞相册图片')
    return HttpResponse.json(createSuccessResponse(null))
  }),

  // 解锁付费相册内容
  http.post('*/web/ai-user/album/unlock', async ({ request }) => {
    console.log('🔓 解锁付费相册内容')
    return HttpResponse.json(createSuccessResponse(null))
  }),

  // 设置默认相册图片
  http.post('*/web/ai-user/set-default-album', async ({ request }) => {
    console.log('👤 设置默认相册图片')
    // 延迟2秒返回
    await new Promise((resolve) => setTimeout(resolve, 2000))
    return HttpResponse.json(createSuccessResponse({ success: true }))
  }),

  // 设置相册图片解锁方式
  http.post('*/web/ai-user/set-album-unlock-price', async ({ request }) => {
    console.log('👤 设置相册图片解锁方式')
    return HttpResponse.json(createSuccessResponse({ success: true }))
  }),

  // 删除相册图片
  http.post('*/web/ai-user/album-del', async ({ request }) => {
    console.log('👤 删除相册图片')
    return HttpResponse.json(createSuccessResponse({ success: true }))
  }),

  http.post('*/web/ai-user-search/base-list', async ({ request }) => {
    console.log('👤 获取AI角色列表')
    return HttpResponse.json(
      createSuccessResponse(
        new Array(5).fill(0).map((_, index) => ({
          aiId: index + 1,
          nickname: `角色${index + 1}`,
          headImg: `https://picsum.photos/108/108?random=${index + 1}`,
          homeImageUrl: `https://picsum.photos/108/108?random=${index + 1}`,
          idCard: `idCard${index + 1}`,
          introduction: `简介${index + 1}`,
          permission: 1,
          roleName: `角色${index + 1}`,
          sex: 1,
          tagName: `标签${index + 1}`,
          birthday: `1990-01-01`,
          characterName: `性格${index + 1}`,
          roleCode: `roleCode${index + 1}`,
          tagCode: `tagCode${index + 1}`,
          characterCode: `characterCode${index + 1}`,
        }))
      )
    )
  }),

  http.post('*/web/ai-user/get-my-ai-user/info', async ({ request }) => {
    console.log('👤 获取AI用户信息')

    // AiUserInfoOutput
    return HttpResponse.json(
      createSuccessResponse({
        aiId: 1,
        nickname: '张三',
        headImg: 'https://hhb.crushlevel.ai/dev/role/17543853962426729.jpg',
        imageUrl: 'https://hhb.crushlevel.ai/dev/role/17543853962426729.jpg',
        introduction: '简介简介简介简介简介简介',
        permission: 1,
        roleName: '角色1',
        sex: 1,
        tagName: '标签1',
        roleCode: 'roleCode1',
        tagCode: 'tagCode1',
        characterCode: 'characterCode1',
        characterName: '性格1',
        birthday: '1990-01-01',
        aiUserExt: {
          profile: 'profile: AI生成内容',
          imageDesc: 'imageDesc: AI生成内容',
          imageReferenceUrl: 'https://hhb.crushlevel.ai/dev/role/17543853962426729.jpg',
          imageStyleCode: 'imageStyleCode1',
          imageStyleUrl: 'https://hhb.crushlevel.ai/dev/role/17543853962426729.jpg',
          dialoguePrologue: 'prologue: AI生成内容',
          dialogueStyle: 'style: AI生成内容',
          dialogueTimbreCode: 'timbreCode1',
          dialogueTimbreUrl: 'https://hhb.crushlevel.ai/dev/role/17543853962426729.jpg',
        },
      } as AiUserInfoOutput)
    )
  }),
]
