import { describe, it, expect } from 'vitest';
import {
  makePort,
  makeClient,
  makeCompany,
  makeBerth,
  makeYacht,
  makeMembership,
  makeTenancy,
  makeOwnershipTransfer,
} from '../helpers/factories';
import { db } from '@/lib/db';
import { yachtOwnershipHistory } from '@/lib/db/schema';
import { eq, isNull, and } from 'drizzle-orm';

describe('factory helpers smoke', () => {
  it('makeMembership inserts a row', async () => {
    const port = await makePort();
    const client = await makeClient({ portId: port.id });
    const company = await makeCompany({ portId: port.id });
    const m = await makeMembership({ companyId: company.id, clientId: client.id });
    expect(m.role).toBe('director');
    expect(m.endDate).toBeNull();
  });

  it('makeTenancy inserts a row in any status', async () => {
    const port = await makePort();
    const berth = await makeBerth({ portId: port.id });
    const client = await makeClient({ portId: port.id });
    const yacht = await makeYacht({
      portId: port.id,
      ownerType: 'client',
      ownerId: client.id,
    });
    const r = await makeTenancy({
      berthId: berth.id,
      portId: port.id,
      clientId: client.id,
      yachtId: yacht.id,
      status: 'pending',
    });
    expect(r.status).toBe('pending');
  });

  it('makeOwnershipTransfer closes prior history and opens new', async () => {
    const port = await makePort();
    const clientA = await makeClient({ portId: port.id });
    const clientB = await makeClient({ portId: port.id });
    const yacht = await makeYacht({
      portId: port.id,
      ownerType: 'client',
      ownerId: clientA.id,
    });

    const { yacht: updated } = await makeOwnershipTransfer({
      yachtId: yacht.id,
      newOwner: { type: 'client', id: clientB.id },
    });
    expect(updated.currentOwnerId).toBe(clientB.id);

    const open = await db
      .select()
      .from(yachtOwnershipHistory)
      .where(
        and(eq(yachtOwnershipHistory.yachtId, yacht.id), isNull(yachtOwnershipHistory.endDate)),
      );
    expect(open).toHaveLength(1);
    expect(open[0]!.ownerId).toBe(clientB.id);
  });
});
