import { register } from '@/services/mock/registry'
import { endpoints } from '@/services/api/endpoints'
import { adminUsers, roles } from '@/services/mock/fixtures/admin-users'
import {
  filterDateRange,
  filterItems,
  findOrThrow,
  isoNow,
  makeId,
  paginate,
  removeById,
  updateById,
} from '@/services/mock/helpers'

register('GET', endpoints.getApprovedUsers, ({ query }) => {
  let list = filterItems(adminUsers, query, {
    name: (item, v) =>
      (item.name || `${item.firstName} ${item.lastName}`)
        .toLowerCase()
        .includes(String(v).toLowerCase()),
    nationalCode: 'includes',
    phoneNumber: 'includes',
    roleId: (item, v) => String(item.roleId) === String(v),
    status: (item, v) => String(item.status) === String(v),
  })
  list = filterDateRange(list, query)
  const { data: items, meta } = paginate(list, query)
  return {
    success: true,
    message: 'OK',
    data: { items, meta },
  }
})

register('GET', endpoints.showUserDetails, ({ params }) => ({
  success: true,
  message: 'OK',
  data: findOrThrow(adminUsers, params.id),
}))

register('GET', endpoints.getUserRegisterData, ({ params }) => {
  const user = findOrThrow(adminUsers, params.id)
  return {
    success: true,
    message: 'OK',
    data: [
      { key: 'educationStatus', value: 'seminary_student' },
      { key: 'seminaryLevel', value: 'level_3' },
      { key: 'universityLevel', value: 'not_applicable' },
      { key: 'universityName', value: 'حوزه علمیه قم' },
      { key: 'fieldOfStudy', value: 'فقه و اصول' },
      { key: 'activitySummary', value: 'برگزاری جلسات قرآن و حدیث به صورت هفتگی.' },
      { key: 'specializedTopics', value: 'تربیت دینی نوجوانان' },
      { key: 'propagationExperienceYears', value: 6 },
      { key: 'propagationMethodDescription', value: 'محوریت بیان داستان‌های قرآنی.' },
      {
        key: 'propagationPlatforms',
        value: [
          { platform: 'home_gathering_regular', platform_details: null },
          { platform: 'online', platform_details: 'کانال اینستاگرام @example' },
        ],
      },
      { key: 'responseToLowSatisfaction', value: 'change_the_method' },
      { key: 'responseToSessionCancellation', value: 'teach_how_to_reduce_costs' },
      { key: 'responseToAudienceConflict', value: 'divide_the_crowd' },
      { key: 'responseToCompetingPropagator', value: 'strengthen_yourself' },
      { key: 'responseToCompetingPropagatorDescription', value: null },
      { key: 'relevantCertificates', value: 'سطح ۳ حوزوی، تدریس قرآن' },
      { key: 'hijabApproach', value: 'گفتگوی همدلانه و آموزش‌محور.' },
      { key: 'provinceId', value: user.address?.province?.id ?? 1 },
      { key: 'cityId', value: user.address?.city?.id ?? 101 },
      { key: 'address', value: user.address?.address || 'تهران، خیابان نمونه' },
      { key: 'avatar', value: null },
      { key: 'avatarId', value: null },
    ],
  }
})

register('POST', endpoints.addNewUser, ({ data }) => {
  const id = makeId()
  const roleByName = (n) => roles.find((r) => r.name === n)
  const role =
    (data.role ? roleByName(data.role) : null) ||
    (Array.isArray(data.roles) && data.roles[0] ? roleByName(data.roles[0]) : null) ||
    roles.find((r) => r.id === Number(data.roleId)) ||
    null
  const province = data.provinceId ? { id: data.provinceId, name: '' } : null
  const city = data.cityId ? { id: data.cityId, name: '' } : null
  const name = data.name || `${data.firstName || ''} ${data.lastName || ''}`.trim()
  const [firstName, ...rest] = name.split(' ')
  const lastName = rest.join(' ')
  const phoneNumber = data.phoneNumber || ''
  const user = {
    // --- spec ---
    id,
    name,
    email: data.email || '',
    phone: data.phone || (phoneNumber ? phoneNumber.replace(/^0/, '+98') : null),
    roles: Array.isArray(data.roles) ? data.roles : role ? [role.name] : [],
    avatarUrl: '',
    avatarDownloadUrl: null,
    createdAt: isoNow(),
    birthday: data.birthday || null,

    // --- ui-only ---
    firstName,
    lastName,
    fullName: name,
    phoneNumber,
    nationalCode: data.nationalCode || '',
    status: 'approved',
    roleId: role?.id,
    address: { address: data.address || '', province, city },
    profile: {
      bio: data.bio || '',
      maritalStatus: data.marriageStatus || data.maritalStatus || '',
      gender: data.gender || '',
      avatarId: data.avatarId || null,
    },
  }
  adminUsers.unshift(user)
  return {
    success: true,
    message: 'User created.',
    data: user,
  }
})

register('PATCH', endpoints.updateUser, ({ params, data }) => {
  const roleByName = (n) => roles.find((r) => r.name === n)
  const role =
    (Array.isArray(data.roles) && data.roles[0] ? roleByName(data.roles[0]) : null) ||
    roles.find((r) => r.id === Number(data.roleId)) ||
    null
  const name = data.name ?? `${data.firstName ?? ''} ${data.lastName ?? ''}`.trim()
  const [firstName, ...rest] = name.split(' ')
  const lastName = rest.join(' ')
  const phoneNumber = data.phoneNumber ?? ''
  const patch = {
    // --- spec ---
    name,
    email: data.email,
    phone: data.phone ?? (phoneNumber ? phoneNumber.replace(/^0/, '+98') : undefined),
    roles: Array.isArray(data.roles) ? data.roles : role ? [role.name] : [],
    birthday: data.birthday ?? null,

    // --- ui-only ---
    firstName,
    lastName,
    fullName: name,
    phoneNumber,
    nationalCode: data.nationalCode,
    roleId: role?.id,
    address: {
      address: data.address || '',
      province: data.provinceId ? { id: data.provinceId, name: '' } : null,
      city: data.cityId ? { id: data.cityId, name: '' } : null,
    },
    profile: {
      bio: data.bio || '',
      maritalStatus: data.marriageStatus ?? data.maritalStatus ?? '',
      gender: data.gender || '',
      avatarId: data.avatarId || null,
    },
  }
  const updated = updateById(adminUsers, params.id, patch)
  return {
    success: true,
    message: 'User updated.',
    data: updated,
  }
})

register('PATCH', endpoints.updateUserRole, ({ params, data }) => {
  const byName = (n) => roles.find((r) => r.name === n)
  const nextRoleNames = Array.isArray(data.roles)
    ? data.roles.filter(Boolean)
    : data.role
    ? [data.role]
    : data.roleId
    ? [roles.find((r) => r.id === Number(data.roleId))?.name].filter(Boolean)
    : []
  const primary = nextRoleNames[0] ? byName(nextRoleNames[0]) : null
  const patch = nextRoleNames.length > 0 ? { roles: nextRoleNames, roleId: primary?.id } : {}
  const updated = updateById(adminUsers, params.id, patch)
  return {
    success: true,
    message: 'Roles updated.',
    data: updated,
  }
})

register('PATCH', endpoints.changeUserStatus, ({ params, data }) => {
  const updated = updateById(adminUsers, params.id, { status: data.status })
  return {
    success: true,
    message: 'User status updated.',
    data: { id: updated.id, name: updated.name, status: updated.status },
  }
})

register('DELETE', endpoints.deleteUser, ({ params }) => {
  removeById(adminUsers, params.id)
  return {
    success: true,
    message: 'User deleted.',
    data: null,
  }
})
