import { test, expect } from '../fixtures/auth.fixture'

/**
 * P0: 认证 API 测试
 *
 * 测试 LeaiAuthController 的三个接口：
 * - GET /leai-auth/token（iframe 主入口）
 * - GET /leai-auth（302 重定向）
 * - GET /leai-auth/refresh-token（Token 刷新）
 */

const API_BASE = process.env.API_BASE_URL || 'http://localhost:8580/api'

test.describe('乐读派认证 API', () => {

  test.describe('GET /leai-auth/token', () => {
    test('未登录 — 返回 401', async ({ request }) => {
      const resp = await request.get(`${API_BASE}/leai-auth/token`)
      expect(resp.status()).toBe(401)
    })

    test('已登录 — 返回 token + orgId + h5Url + phone', async ({ authedApi }) => {
      const resp = await authedApi.get(`${API_BASE}/leai-auth/token`)
      expect(resp.status()).toBe(200)

      const json = await resp.json()
      expect(json.code).toBe(200)
      expect(json.data).toBeDefined()

      const data = json.data
      expect(data).toHaveProperty('token')
      expect(data).toHaveProperty('orgId')
      expect(data).toHaveProperty('h5Url')
      expect(data).toHaveProperty('phone')
      expect(data.token).toBeTruthy()
      expect(data.orgId).toBeTruthy()
      expect(data.h5Url).toContain('http')
    })

    test('返回的 token 为非空字符串', async ({ authedApi }) => {
      const resp = await authedApi.get(`${API_BASE}/leai-auth/token`)
      const json = await resp.json()
      expect(typeof json.data.token).toBe('string')
      expect(json.data.token.length).toBeGreaterThan(10)
    })
  })

  test.describe('GET /leai-auth/refresh-token', () => {
    test('未登录 — 返回 401', async ({ request }) => {
      const resp = await request.get(`${API_BASE}/leai-auth/refresh-token`)
      expect(resp.status()).toBe(401)
    })

    test('已登录 — 刷新成功', async ({ authedApi }) => {
      const resp = await authedApi.get(`${API_BASE}/leai-auth/refresh-token`)
      expect(resp.status()).toBe(200)

      const json = await resp.json()
      expect(json.code).toBe(200)
      expect(json.data).toHaveProperty('token')
      expect(json.data).toHaveProperty('orgId')
      expect(json.data).toHaveProperty('phone')
    })

    test('连续两次刷新返回不同 token', async ({ authedApi }) => {
      const resp1 = await authedApi.get(`${API_BASE}/leai-auth/refresh-token`)
      const json1 = await resp1.json()

      // 短暂等待确保时间戳不同
      await new Promise((r) => setTimeout(r, 100))

      const resp2 = await authedApi.get(`${API_BASE}/leai-auth/refresh-token`)
      const json2 = await resp2.json()

      expect(json1.data.token).toBeTruthy()
      expect(json2.data.token).toBeTruthy()
      // 两次 token 应不同（每次换新 session）
      expect(json1.data.token).not.toBe(json2.data.token)
    })
  })

  test.describe('GET /leai-auth（302 重定向）', () => {
    test('未登录 — 返回 401', async ({ request }) => {
      const resp = await request.get(`${API_BASE}/leai-auth`, {
        maxRedirects: 0,
      })
      // 可能是 401 或 302 到登录页
      expect([302, 401]).toContain(resp.status())
    })

    test('已登录 — 302 重定向到 H5', async ({ authedApi }) => {
      const resp = await authedApi.get(`${API_BASE}/leai-auth`, {
        maxRedirects: 0,
      })
      expect(resp.status()).toBe(302)

      const location = resp.headers()['location']
      expect(location).toBeDefined()
      expect(location).toContain('token=')
      expect(location).toContain('orgId=')
      expect(location).toContain('phone=')
    })

    test('带 returnPath — 重定向 URL 包含 returnPath', async ({ authedApi }) => {
      const resp = await authedApi.get(`${API_BASE}/leai-auth?returnPath=/edit-info/test123`, {
        maxRedirects: 0,
      })
      expect(resp.status()).toBe(302)

      const location = resp.headers()['location']
      expect(location).toContain('returnPath=')
      expect(location).toContain('edit-info')
    })
  })
})
