import { defineStore } from 'pinia'
import type { AdminRole } from '../auth/roles'

export type UserAccount = {
  id: string
  name: string
  email: string
  role: AdminRole
  status: '正常' | '冻结'
  managerName: string
}

export type InviteRequest = {
  id: string
  email: string
  role: AdminRole
  status: '待接受' | '已接受' | '已拒绝' | '已过期'
  invitedAt: string
  acceptedAt?: string
  expiredAt?: string
}

export type RoleChangeRequest = {
  id: string
  userId: string
  currentRole: AdminRole
  targetRole: AdminRole
  reason: string
  status: '待审批' | '已通过' | '已拒绝'
  requestedAt: string
  approvedBy?: string
  decisionAt?: string
  rejectReason?: string
}

const nowIso = () => new Date().toISOString()

export const useUserStore = defineStore('users', {
  state: () => ({
    users: [] as UserAccount[],
    invites: [] as InviteRequest[],
    roleRequests: [] as RoleChangeRequest[]
  }),
  getters: {
    byId: (state) => (id: string) => state.users.find((u) => u.id === id) ?? null,
    pendingRoleRequests: (state) => state.roleRequests.filter((req) => req.status === '待审批')
  },
  actions: {
    init(users: UserAccount[], invites: InviteRequest[], requests: RoleChangeRequest[]) {
      if (this.users.length) return
      this.users = users
      this.invites = invites
      this.roleRequests = requests
    },
    toggleUserStatus(id: string) {
      const user = this.byId(id)
      if (!user) return
      user.status = user.status === '冻结' ? '正常' : '冻结'
    },
    addInvite(email: string, role: AdminRole) {
      const invite: InviteRequest = {
        id: `invite-${Date.now()}`,
        email,
        role,
        status: '待接受',
        invitedAt: nowIso()
      }
      this.invites.unshift(invite)
      return invite
    },
    acceptInvite(id: string) {
      const invite = this.invites.find((item) => item.id === id)
      if (!invite || invite.status !== '待接受') return
      invite.status = '已接受'
      invite.acceptedAt = nowIso()
    },
    resendInvite(id: string) {
      const invite = this.invites.find((item) => item.id === id)
      if (!invite) return
      invite.status = '待接受'
      invite.invitedAt = nowIso()
      invite.expiredAt = undefined
    },
    expireInvite(id: string) {
      const invite = this.invites.find((item) => item.id === id)
      if (!invite || invite.status === '已过期') return
      invite.status = '已过期'
      invite.expiredAt = nowIso()
    },
    requestRoleChange(userId: string, targetRole: AdminRole, reason: string) {
      const user = this.byId(userId)
      if (!user) return null
      const request: RoleChangeRequest = {
        id: `role-${Date.now()}`,
        userId,
        currentRole: user.role,
        targetRole,
        reason,
        status: '待审批',
        requestedAt: nowIso()
      }
      this.roleRequests.unshift(request)
      return request
    },
    approveRoleChange(id: string, approver: string) {
      const request = this.roleRequests.find((item) => item.id === id)
      if (!request || request.status !== '待审批') return
      request.status = '已通过'
      request.approvedBy = approver
      request.decisionAt = nowIso()
      const user = this.byId(request.userId)
      if (user) {
        user.role = request.targetRole
      }
    },
    rejectRoleChange(id: string, approver: string, rejectReason: string) {
      const request = this.roleRequests.find((item) => item.id === id)
      if (!request || request.status !== '待审批') return
      request.status = '已拒绝'
      request.approvedBy = approver
      request.decisionAt = nowIso()
      request.rejectReason = rejectReason
    }
  }
})
