/**
 * D-series: Shopping item RLS — CRUD by role, cross-collective isolation.
 */
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createClientAs, createAdminClient } from '../src/supabase-clients.js';
import { ANA_ID, BORJA_ID, DAVID_ID, EVA_ID, COLLECTIVE_ID, SEED_LIST_ID } from '../src/seed-constants.js';

const admin = createAdminClient();
const createdItemIds: string[] = [];

afterAll(async () => {
	if (createdItemIds.length > 0) {
		await admin.from('shopping_items').delete().in('id', createdItemIds);
	}
});

describe('Shopping item read access', () => {
	it('D-05: member (Borja) can read items in the seed list', async () => {
		const borja = await createClientAs(BORJA_ID);
		const { data, error } = await borja
			.from('shopping_items')
			.select('id, name')
			.eq('list_id', SEED_LIST_ID);
		expect(error).toBeNull();
		expect(data!.length).toBeGreaterThanOrEqual(1);
	});

	it('D-06: guest (David) can read items in the seed list', async () => {
		const david = await createClientAs(DAVID_ID);
		const { data, error } = await david
			.from('shopping_items')
			.select('id')
			.eq('list_id', SEED_LIST_ID);
		expect(error).toBeNull();
		expect(data!.length).toBeGreaterThanOrEqual(1);
	});
});

describe('Shopping item create', () => {
	it('D-07: member (Borja) can add an item', async () => {
		const borja = await createClientAs(BORJA_ID);
		const { data, error } = await borja
			.from('shopping_items')
			.insert({ list_id: SEED_LIST_ID, name: 'Test item', sort_order: 100, created_by: BORJA_ID })
			.select('id')
			.single();
		expect(error).toBeNull();
		expect(data?.id).toBeTruthy();
		if (data?.id) createdItemIds.push(data.id);
	});

	it('D-08: guest (David) cannot add an item', async () => {
		const david = await createClientAs(DAVID_ID);
		const { data, error } = await david
			.from('shopping_items')
			.insert({ list_id: SEED_LIST_ID, name: 'David sneaky item', sort_order: 101, created_by: DAVID_ID })
			.select('id')
			.single();
		expect(data).toBeNull();
		expect(error).not.toBeNull();
	});

	it('D-09: cannot spoof created_by to another user', async () => {
		const borja = await createClientAs(BORJA_ID);
		const { data, error } = await borja
			.from('shopping_items')
			.insert({ list_id: SEED_LIST_ID, name: 'Spoofed item', sort_order: 102, created_by: ANA_ID })
			.select('id')
			.single();
		expect(data).toBeNull();
		expect(error).not.toBeNull();
	});
});

describe('Shopping item update', () => {
	let testItemId: string;

	beforeAll(async () => {
		const { data } = await admin
			.from('shopping_items')
			.insert({ list_id: SEED_LIST_ID, name: 'Update test item', sort_order: 200, created_by: ANA_ID })
			.select('id')
			.single();
		testItemId = data!.id;
		createdItemIds.push(testItemId);
	});

	it('D-10: member (Carmen) can check an item', async () => {
		const carmen = await createClientAs(ANA_ID); // use Ana since Carmen is seeded member
		const { error } = await carmen
			.from('shopping_items')
			.update({ is_checked: true, checked_by: ANA_ID, checked_at: new Date().toISOString() })
			.eq('id', testItemId);
		expect(error).toBeNull();
		const { data } = await admin.from('shopping_items').select('is_checked').eq('id', testItemId).single();
		expect(data?.is_checked).toBe(true);
	});

	it('D-11: guest (David) cannot update an item', async () => {
		const david = await createClientAs(DAVID_ID);
		await david
			.from('shopping_items')
			.update({ is_checked: false })
			.eq('id', testItemId);
		// Verify no change — item should still be checked
		const { data } = await admin.from('shopping_items').select('is_checked').eq('id', testItemId).single();
		expect(data?.is_checked).toBe(true);
	});

	it('D-12: member can uncheck an item', async () => {
		const borja = await createClientAs(BORJA_ID);
		const { error } = await borja
			.from('shopping_items')
			.update({ is_checked: false, checked_by: null, checked_at: null })
			.eq('id', testItemId);
		expect(error).toBeNull();
		const { data } = await admin.from('shopping_items').select('is_checked').eq('id', testItemId).single();
		expect(data?.is_checked).toBe(false);
	});
});

describe('Shopping item delete', () => {
	let testItemId: string;

	beforeAll(async () => {
		const { data } = await admin
			.from('shopping_items')
			.insert({ list_id: SEED_LIST_ID, name: 'Delete test item', sort_order: 300, created_by: ANA_ID })
			.select('id')
			.single();
		testItemId = data!.id;
		createdItemIds.push(testItemId);
	});

	it('D-13: guest (David) cannot delete an item', async () => {
		const david = await createClientAs(DAVID_ID);
		await david.from('shopping_items').delete().eq('id', testItemId);
		const { data } = await admin.from('shopping_items').select('id').eq('id', testItemId).single();
		expect(data?.id).toBe(testItemId);
	});

	it('D-14: member (Borja) can hard-delete an item', async () => {
		const borja = await createClientAs(BORJA_ID);
		const { error } = await borja.from('shopping_items').delete().eq('id', testItemId);
		expect(error).toBeNull();
		const { data } = await admin.from('shopping_items').select('id').eq('id', testItemId);
		expect(data).toHaveLength(0);

		const idx = createdItemIds.indexOf(testItemId);
		if (idx !== -1) createdItemIds.splice(idx, 1);
	});
});

describe('Cross-collective item isolation', () => {
	let otherCollectiveId: string;
	let otherListId: string;
	let otherItemId: string;

	beforeAll(async () => {
		const { data: collective } = await admin
			.from('collectives')
			.insert({ name: 'Item isolation collective', emoji: '🔒', created_by: EVA_ID })
			.select('id')
			.single();
		otherCollectiveId = collective!.id;

		await admin
			.from('collective_members')
			.insert({ collective_id: otherCollectiveId, user_id: EVA_ID, role: 'admin' });

		const { data: list } = await admin
			.from('shopping_lists')
			.insert({ collective_id: otherCollectiveId, name: 'Private list', created_by: EVA_ID })
			.select('id')
			.single();
		otherListId = list!.id;

		const { data: item } = await admin
			.from('shopping_items')
			.insert({ list_id: otherListId, name: 'Private item', sort_order: 1, created_by: EVA_ID })
			.select('id')
			.single();
		otherItemId = item!.id;
	});

	afterAll(async () => {
		if (otherCollectiveId) {
			await admin.from('collectives').delete().eq('id', otherCollectiveId);
		}
	});

	it('D-15: Borja cannot read items from a different collective', async () => {
		const borja = await createClientAs(BORJA_ID);
		const { data } = await borja
			.from('shopping_items')
			.select('id')
			.eq('id', otherItemId);
		expect(data).toHaveLength(0);
	});

	it('D-16: Borja cannot delete an item from a different collective', async () => {
		const borja = await createClientAs(BORJA_ID);
		await borja.from('shopping_items').delete().eq('id', otherItemId);
		const { data } = await admin.from('shopping_items').select('id').eq('id', otherItemId).single();
		expect(data?.id).toBe(otherItemId);
	});
});
