describe('Registration Flow', () => {
  const ADMIN_TOKEN = 'c86ae7afbe10fabe3c1d5e1a7fee74feaadfd5dc7be2ab62'
  const authHeaders = { Authorization: `Bearer ${ADMIN_TOKEN}` }
  const TEST_USER = 'cypress_test_register_' + Date.now()

  it('can register a new user via API', () => {
    cy.request({
      method: 'POST', url: '/api/register',
      body: { username: TEST_USER, password: 'test1234', display_name: 'Cypress注册测试' },
      failOnStatusCode: false
    }).then(res => {
      // Registration may or may not be implemented
      if (res.status === 200 || res.status === 201) {
        expect(res.body).to.have.property('token')
      }
    })
  })

  it('registered user can authenticate', () => {
    cy.request({
      method: 'POST', url: '/api/login',
      body: { username: TEST_USER, password: 'test1234' },
      failOnStatusCode: false
    }).then(res => {
      if (res.status === 200) {
        expect(res.body).to.have.property('token')
        expect(res.body.token).to.be.a('string')
      }
    })
  })

  it('rejects duplicate username', () => {
    cy.request({
      method: 'POST', url: '/api/register',
      body: { username: TEST_USER, password: 'another123', display_name: 'Duplicate' },
      failOnStatusCode: false
    }).then(res => {
      // Should fail with 400 or 409
      if (res.status !== 404) { // 404 means register endpoint doesn't exist
        expect(res.status).to.be.oneOf([400, 409, 422])
      }
    })
  })

  after(() => {
    // Cleanup: delete test user via admin
    cy.request({ url: '/api/users', headers: authHeaders, failOnStatusCode: false }).then(res => {
      if (res.status === 200) {
        const testUser = res.body.find(u => u.username === TEST_USER)
        if (testUser) {
          cy.request({ method: 'DELETE', url: `/api/users/${testUser.id}`, headers: authHeaders, failOnStatusCode: false })
        }
      }
    })
  })
})
