import { describe, it, expect } from 'vitest';

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

const createMockLeague = (overrides: Partial<{
  id: string;
  name: string;
  createdBy: string;
  isPublicDraftBoard: boolean;
}> = {}) => ({
  id: 'league-1',
  name: 'Test League',
  createdBy: 'user-1',
  currentSeasonId: 'season-1',
  isPublicDraftBoard: false,
  createdAt: new Date('2025-01-01'),
  updatedAt: new Date('2025-01-01'),
  ...overrides,
});

const createMockSeason = (overrides: Partial<{
  id: string;
  leagueId: string;
  status: 'pre_draft' | 'draft' | 'active' | 'completed';
}> = {}) => ({
  id: 'season-1',
  leagueId: 'league-1',
  year: 2025,
  status: 'draft' as const,
  templateId: null,
  draftRounds: 20,
  flexSpots: 0,
  draftDateTime: null,
  draftInitialTime: 120,
  draftIncrementTime: 15,
  currentPickNumber: 5,
  draftStartedAt: new Date('2025-12-01T19:00:00'),
  draftPaused: false,
  inviteCode: 'TEST123',
  pointsFor1st: 100,
  pointsFor2nd: 70,
  pointsFor3rd: 50,
  pointsFor4th: 40,
  pointsFor5th: 25,
  pointsFor6th: 25,
  pointsFor7th: 15,
  pointsFor8th: 15,
  createdAt: new Date('2025-01-01'),
  updatedAt: new Date('2025-01-01'),
  ...overrides,
});

// Simulates the access-control logic extracted from the draft board loader.
// Returns null if access is granted, or the error message if access is denied.
async function checkDraftBoardAccess(opts: {
  leagueId: string;
  seasonId: string;
  season: ReturnType<typeof createMockSeason> & { league: ReturnType<typeof createMockLeague> };
  userId: string | null;
  isCommissioner: boolean;
  hasTeam: boolean;
}): Promise<{ status: number; message: string } | null> {
  const { leagueId, season, userId, isCommissioner, hasTeam } = opts;

  // Validate leagueId matches the season's actual league
  if (season.leagueId !== leagueId) {
    return { status: 404, message: 'Season not found' };
  }

  // Public boards: no auth required
  if (season.league.isPublicDraftBoard) {
    return null;
  }

  // Private: must be authenticated
  if (!userId) {
    return { status: 403, message: 'This draft board is not public' };
  }

  // Private: must be commissioner or team owner
  if (!isCommissioner && !hasTeam) {
    return { status: 403, message: "You don't have access to this draft board" };
  }

  return null;
}

// ---------------------------------------------------------------------------
// leagueId / seasonId relationship validation
// ---------------------------------------------------------------------------

describe('Draft Board Access - League/Season Validation', () => {
  const league = createMockLeague({ id: 'league-1' });

  it('should return 404 when seasonId belongs to a different league', async () => {
    const season = { ...createMockSeason({ leagueId: 'league-999' }), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: 'user-1',
      isCommissioner: true,
      hasTeam: false,
    });

    expect(result).toEqual({ status: 404, message: 'Season not found' });
  });

  it('should not 404 when seasonId belongs to the correct league', async () => {
    const season = { ...createMockSeason({ leagueId: 'league-1' }), league: createMockLeague({ isPublicDraftBoard: true }) };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: null,
      isCommissioner: false,
      hasTeam: false,
    });

    expect(result).toBeNull();
  });
});

// ---------------------------------------------------------------------------
// Public board
// ---------------------------------------------------------------------------

describe('Draft Board Access - Public Board', () => {
  const league = createMockLeague({ isPublicDraftBoard: true });

  it('should allow unauthenticated access to a public board', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: null,
      isCommissioner: false,
      hasTeam: false,
    });

    expect(result).toBeNull();
  });

  it('should allow authenticated non-member access to a public board', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: 'outsider-user',
      isCommissioner: false,
      hasTeam: false,
    });

    expect(result).toBeNull();
  });

  it('should allow team-owner access to a public board', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: 'owner-user',
      isCommissioner: false,
      hasTeam: true,
    });

    expect(result).toBeNull();
  });

  it('should allow commissioner access to a public board', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: 'commissioner-user',
      isCommissioner: true,
      hasTeam: false,
    });

    expect(result).toBeNull();
  });
});

// ---------------------------------------------------------------------------
// Private board - unauthenticated
// ---------------------------------------------------------------------------

describe('Draft Board Access - Private Board, Unauthenticated', () => {
  const league = createMockLeague({ isPublicDraftBoard: false });

  it('should return 403 for unauthenticated requests to a private board', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: null,
      isCommissioner: false,
      hasTeam: false,
    });

    expect(result).toEqual({ status: 403, message: 'This draft board is not public' });
  });

  it('should use "not public" wording for the unauthenticated case', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: null,
      isCommissioner: false,
      hasTeam: false,
    });

    expect(result?.message).toBe('This draft board is not public');
  });
});

// ---------------------------------------------------------------------------
// Private board - authenticated non-member
// ---------------------------------------------------------------------------

describe('Draft Board Access - Private Board, Authenticated Non-Member', () => {
  const league = createMockLeague({ isPublicDraftBoard: false });

  it('should return 403 for a logged-in user with no team and no commissioner role', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: 'outsider-user',
      isCommissioner: false,
      hasTeam: false,
    });

    expect(result?.status).toBe(403);
  });

  it('should use "access" wording (not "not public") for authenticated non-members', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: 'outsider-user',
      isCommissioner: false,
      hasTeam: false,
    });

    expect(result?.message).toBe("You don't have access to this draft board");
    expect(result?.message).not.toBe('This draft board is not public');
  });
});

// ---------------------------------------------------------------------------
// Private board - commissioner access
// ---------------------------------------------------------------------------

describe('Draft Board Access - Private Board, Commissioner', () => {
  const league = createMockLeague({ isPublicDraftBoard: false });

  it('should allow a commissioner without a team to view the board', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: 'commissioner-user',
      isCommissioner: true,
      hasTeam: false,
    });

    expect(result).toBeNull();
  });

  it('should allow a commissioner who also owns a team to view the board', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: 'commissioner-owner',
      isCommissioner: true,
      hasTeam: true,
    });

    expect(result).toBeNull();
  });
});

// ---------------------------------------------------------------------------
// Private board - team owner access
// ---------------------------------------------------------------------------

describe('Draft Board Access - Private Board, Team Owner', () => {
  const league = createMockLeague({ isPublicDraftBoard: false });

  it('should allow a team owner who is not a commissioner to view the board', async () => {
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: 'owner-user',
      isCommissioner: false,
      hasTeam: true,
    });

    expect(result).toBeNull();
  });
});

// ---------------------------------------------------------------------------
// isPublicDraftBoard flag semantics
// ---------------------------------------------------------------------------

describe('Draft Board Access - isPublicDraftBoard Flag', () => {
  it('should skip auth check entirely when isPublicDraftBoard is true', async () => {
    const league = createMockLeague({ isPublicDraftBoard: true });
    const season = { ...createMockSeason(), league };

    // Even with userId=null AND isCommissioner=false AND hasTeam=false
    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: null,
      isCommissioner: false,
      hasTeam: false,
    });

    // Access granted without any auth check
    expect(result).toBeNull();
  });

  it('should require auth when isPublicDraftBoard is false', async () => {
    const league = createMockLeague({ isPublicDraftBoard: false });
    const season = { ...createMockSeason(), league };

    const result = await checkDraftBoardAccess({
      leagueId: 'league-1',
      seasonId: 'season-1',
      season,
      userId: null,
      isCommissioner: false,
      hasTeam: false,
    });

    expect(result?.status).toBe(403);
  });
});
