import { beforeEach, describe, expect, it, vi } from 'vitest'

const getMock = vi.fn()
const postMock = vi.fn()
const delMock = vi.fn()

vi.mock('@/lib/http/client', () => ({
  get: getMock,
  post: postMock,
  del: delMock,
}))

describe('social account service', () => {
  beforeEach(() => {
    getMock.mockReset()
    postMock.mockReset()
    delMock.mockReset()
    getMock.mockResolvedValue([])
    postMock.mockResolvedValue({ auth_url: 'https://oauth.example.com', state: 'state-demo' })
    delMock.mockResolvedValue(undefined)
  })

  it('lists current user social accounts', async () => {
    const { listSocialAccounts } = await import('./social-accounts')

    await listSocialAccounts()

    expect(getMock).toHaveBeenCalledWith('/users/me/social-accounts')
  })

  it('normalizes object-wrapped social account payloads', async () => {
    getMock.mockResolvedValue({
      social_accounts: [
        {
          provider: 'github',
          provider_user_id: '123',
          provider_username: 'octocat',
          bound_at: '2026-03-27 20:00:00',
        },
      ],
    })

    const { listSocialAccounts } = await import('./social-accounts')
    const result = await listSocialAccounts()

    expect(result).toEqual([
      expect.objectContaining({
        provider: 'github',
        provider_username: 'octocat',
      }),
    ])
  })

  it('starts social binding with the current verification payload', async () => {
    const { startSocialBinding } = await import('./social-accounts')

    await startSocialBinding({
      provider: 'github',
      return_to: '/profile/security',
      current_password: 'SecurePass123',
    })

    expect(postMock).toHaveBeenCalledWith('/users/me/bind-social', {
      provider: 'github',
      return_to: '/profile/security',
      current_password: 'SecurePass123',
    })
  })

  it('unbinds a social account with optional verification data', async () => {
    const { unbindSocialAccount } = await import('./social-accounts')

    await unbindSocialAccount('github', { totp_code: '123456' })

    expect(delMock).toHaveBeenCalledWith('/users/me/bind-social/github', {
      body: { totp_code: '123456' },
    })
  })
})
