import { isAuthRequest } from '@/constants/system'
import { EMAIL_REGEX, PASSWORD_REGEX } from '@/constants/regex'
import { decodeJwtPayloadWithoutVerification } from '@/util'
import { getPasswordChecks, isPasswordValid } from '@/util/password-validation'
// Password/confirmPassword match refinement is on BaseSignUpRequestSchema only;
// SignUpRequestSchema omits confirmPassword (API body + recaptchaToken).
import { BaseSignUpRequestSchema } from '@/services/auth/auth.schema'

const validBaseSignUp = {
  full_name: 'Nguyen Van A',
  password: 'ValidPass1!',
  confirmPassword: 'ValidPass1!',
  account_type: 'BUSINESS_OWNER' as const,
  company_name: 'Company Limited',
  company_email: 'user@company.com',
  business_type: 'Retail',
  phone_number: '0901234567',
  tax_code: '0123456789',
  tnc_accepted: true as const,
}

describe('_tests_/security', () => {
  describe('isAuthRequest — URL classification', () => {
    it.each([
      ['/token', true],
      ['/api/v1/token', true],
      ['/auth/oauth/token', true],
      ['/application/list', false],
      ['/internal/profile', false],
    ] as const)('%s → %s', (url, expected) => {
      expect(isAuthRequest(url)).toBe(expected)
    })

    it.each([undefined, ''] as const)(
      'negative: undefined or empty URL → false',
      (url) => {
        expect(isAuthRequest(url)).toBe(false)
      },
    )
  })

  describe('EMAIL_REGEX — injection / contract', () => {
    it.each([
      ['user@domain.com', true],
      ['a@b.co', true],
      ['bad@@x.com', false],
      ['<script>alert(1)</script>@x.com', false],
      ['', false],
    ] as const)('%s → %s', (value, expected) => {
      expect(EMAIL_REGEX.test(value)).toBe(expected)
    })
  })

  describe('PASSWORD_REGEX — complexity', () => {
    it.each([
      ['ValidPass1!', true],
      ['Aa1!aaaa', true],
      ['short1!', false],
      ['12345678', false],
      ['password', false],
      ['NoDigit!', false],
      ['nocaps1!', false],
    ] as const)('PASSWORD_REGEX(%s) → %s', (pwd, ok) => {
      expect(PASSWORD_REGEX.test(pwd)).toBe(ok)
    })
  })

  describe('decodeJwtPayloadWithoutVerification', () => {
    it.each(['', 'random', 'onlyone.part', 'no.payload.here.extra'] as const)(
      'negative: %s → null',
      (input) => {
        expect(decodeJwtPayloadWithoutVerification(input)).toBeNull()
      },
    )

    it('happy path: decodes JWT body from fixture token substring', () => {
      const token =
        'eyJhbGciOiJIUzI1NiJ9.' +
        btoa(JSON.stringify({ sub: 'u1', exp: 9999999999 })) +
        '.sig'

      const out = decodeJwtPayloadWithoutVerification(token)
      expect(out).toEqual(expect.objectContaining({ sub: 'u1' }))
    })
  })

  describe('password strength helpers', () => {
    it.each(['weak', '12345678', 'Password1'] as const)(
      'weak candidate %s fails isPasswordValid',
      (pwd) => {
        expect(isPasswordValid(getPasswordChecks(pwd))).toBe(false)
      },
    )

    it('happy path: strong password satisfies all checks', () => {
      const strong = getPasswordChecks('ValidPass1!')
      expect(isPasswordValid(strong)).toBe(true)
    })
  })

  describe('BaseSignUpRequestSchema — confirmPassword refinement', () => {
    it('happy path: matching passwords pass parse', () => {
      expect(BaseSignUpRequestSchema.safeParse(validBaseSignUp).success).toBe(
        true,
      )
    })

    it('negative: mismatched confirmPassword fails with issue on confirmPassword', () => {
      const result = BaseSignUpRequestSchema.safeParse({
        ...validBaseSignUp,
        confirmPassword: 'OtherPass1!',
      })
      expect(result.success).toBe(false)
      if (!result.success) {
        const paths = result.error.issues.map((i) => i.path.join('.'))
        expect(paths.some((p) => p.includes('confirmPassword'))).toBe(true)
      }
    })
  })
})
