/**
 * Unit tests for referrals module — types + validation.
 */

import { describe, it, expect } from 'vitest';
import { CreateReferralSchema, UpdateReferralStatusSchema } from './types.js';

describe('CreateReferralSchema', () => {
  it('accepts valid input with required fields', () => {
    const result = CreateReferralSchema.safeParse({
      referrerId: 'user_abc',
      referrerEmail: 'alice@example.com',
      referredEmail: 'bob@example.com',
    });
    expect(result.success).toBe(true);
    if (result.success) {
      expect(result.data.referrerRewardTokens).toBe(1000);
      expect(result.data.referredRewardTokens).toBe(500);
    }
  });

  it('accepts custom reward amounts', () => {
    const result = CreateReferralSchema.safeParse({
      referrerId: 'user_abc',
      referrerEmail: 'alice@example.com',
      referredEmail: 'bob@example.com',
      referrerRewardTokens: 2000,
      referredRewardTokens: 1000,
    });
    expect(result.success).toBe(true);
    if (result.success) {
      expect(result.data.referrerRewardTokens).toBe(2000);
      expect(result.data.referredRewardTokens).toBe(1000);
    }
  });

  it('rejects invalid referrer email', () => {
    const result = CreateReferralSchema.safeParse({
      referrerId: 'user_abc',
      referrerEmail: 'not-an-email',
      referredEmail: 'bob@example.com',
    });
    expect(result.success).toBe(false);
  });

  it('rejects missing referrerId', () => {
    const result = CreateReferralSchema.safeParse({
      referrerEmail: 'alice@example.com',
      referredEmail: 'bob@example.com',
    });
    expect(result.success).toBe(false);
  });

  it('rejects negative reward tokens', () => {
    const result = CreateReferralSchema.safeParse({
      referrerId: 'user_abc',
      referrerEmail: 'alice@example.com',
      referredEmail: 'bob@example.com',
      referrerRewardTokens: -100,
    });
    expect(result.success).toBe(false);
  });
});

describe('UpdateReferralStatusSchema', () => {
  it('accepts valid status update', () => {
    const result = UpdateReferralStatusSchema.safeParse({
      status: 'signed_up',
      referredUserId: 'user_xyz',
    });
    expect(result.success).toBe(true);
  });

  it('accepts rewarded status with flags', () => {
    const result = UpdateReferralStatusSchema.safeParse({
      status: 'rewarded',
      referrerRewarded: true,
      referredRewarded: true,
    });
    expect(result.success).toBe(true);
  });

  it('rejects invalid status value', () => {
    const result = UpdateReferralStatusSchema.safeParse({ status: 'cancelled' });
    expect(result.success).toBe(false);
  });

  it('rejects missing status', () => {
    const result = UpdateReferralStatusSchema.safeParse({});
    expect(result.success).toBe(false);
  });
});
