import { describe, expect, it, vi } from 'vitest'
import { buildEmailPasswordApiOverrides } from '../auth-session-payload'

describe('auth-session-payload', () => {
  it('stamps email, default plan, and default role onto successful sign-up and sign-in sessions', async () => {
    const mergeOnSignUp = vi.fn(async () => {})
    const mergeOnSignIn = vi.fn(async () => {})

    const overrides = buildEmailPasswordApiOverrides({
      signUpPOST: vi.fn(async (_input: unknown) => ({
        status: 'OK',
        user: {
          emails: ['Operator@HyperTwist.App'],
        },
        session: {
          mergeIntoAccessTokenPayload: mergeOnSignUp,
        },
      })),
      signInPOST: vi.fn(async (_input: unknown) => ({
        status: 'OK',
        user: {
          emails: ['Operator@HyperTwist.App'],
        },
        session: {
          mergeIntoAccessTokenPayload: mergeOnSignIn,
        },
      })),
    }, {
      defaultPlan: 'free',
      defaultRole: 'operator',
    })

    await overrides.signUpPOST?.({})
    await overrides.signInPOST?.({})

    expect(mergeOnSignUp).toHaveBeenCalledWith({
      email: 'operator@hypertwist.app',
      plan: 'free',
      role: 'operator',
    })
    expect(mergeOnSignIn).toHaveBeenCalledWith({
      email: 'operator@hypertwist.app',
      plan: 'free',
      role: 'operator',
    })
  })

  it('does not stamp payload fields when the auth response is not successful', async () => {
    const mergeIntoAccessTokenPayload = vi.fn(async () => {})

    const overrides = buildEmailPasswordApiOverrides({
      signInPOST: vi.fn(async (_input: unknown) => ({
        status: 'WRONG_CREDENTIALS_ERROR',
        user: {
          emails: ['operator@hypertwist.app'],
        },
        session: {
          mergeIntoAccessTokenPayload,
        },
      })),
    }, {
      defaultPlan: 'free',
      defaultRole: 'operator',
    })

    await overrides.signInPOST?.({})

    expect(mergeIntoAccessTokenPayload).not.toHaveBeenCalled()
  })
})
