import { describe, it, expect } from 'vitest';
import { eq } from 'drizzle-orm';
import {
  createPending,
  activate,
  endTenancy,
  cancel,
  listTenancies,
} from '@/lib/services/berth-tenancies.service';
import {
  makePort,
  makeClient,
  makeBerth,
  makeYacht,
  makeCompany,
  makeAuditMeta,
} from '../../helpers/factories';
import { db } from '@/lib/db';
import { companyMemberships } from '@/lib/db/schema/companies';

// ─── createPending ───────────────────────────────────────────────────────────

describe('berth-tenancies.service - createPending', () => {
  it('creates pending reservation for client-owned yacht', 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 reservation = await createPending(
      port.id,
      {
        berthId: berth.id,
        clientId: client.id,
        yachtId: yacht.id,
        startDate: new Date(),
        tenureType: 'permanent',
      },
      makeAuditMeta({ portId: port.id }),
    );

    expect(reservation.status).toBe('pending');
    expect(reservation.berthId).toBe(berth.id);
    expect(reservation.clientId).toBe(client.id);
    expect(reservation.yachtId).toBe(yacht.id);
    expect(reservation.portId).toBe(port.id);
    expect(reservation.tenureType).toBe('permanent');
  });

  it('creates pending for company-owned yacht when client is a company member', async () => {
    const port = await makePort();
    const berth = await makeBerth({ portId: port.id });
    const company = await makeCompany({ portId: port.id });
    const client = await makeClient({ portId: port.id });
    const yacht = await makeYacht({
      portId: port.id,
      ownerType: 'company',
      ownerId: company.id,
    });

    // Active membership (no endDate).
    await db.insert(companyMemberships).values({
      companyId: company.id,
      clientId: client.id,
      role: 'director',
      startDate: new Date(),
    });

    const reservation = await createPending(
      port.id,
      {
        berthId: berth.id,
        clientId: client.id,
        yachtId: yacht.id,
        startDate: new Date(),
        tenureType: 'permanent',
      },
      makeAuditMeta({ portId: port.id }),
    );

    expect(reservation.status).toBe('pending');
    expect(reservation.clientId).toBe(client.id);
  });

  it('rejects when yacht does not belong to client (no membership)', async () => {
    const port = await makePort();
    const berth = await makeBerth({ portId: port.id });
    const ownerClient = await makeClient({ portId: port.id });
    const otherClient = await makeClient({ portId: port.id });
    const yacht = await makeYacht({
      portId: port.id,
      ownerType: 'client',
      ownerId: ownerClient.id,
    });

    await expect(
      createPending(
        port.id,
        {
          berthId: berth.id,
          clientId: otherClient.id,
          yachtId: yacht.id,
          startDate: new Date(),
          tenureType: 'permanent',
        },
        makeAuditMeta({ portId: port.id }),
      ),
    ).rejects.toThrow(/yacht does not belong/i);
  });

  it('rejects when company-owned yacht client has an ended membership', async () => {
    const port = await makePort();
    const berth = await makeBerth({ portId: port.id });
    const company = await makeCompany({ portId: port.id });
    const client = await makeClient({ portId: port.id });
    const yacht = await makeYacht({
      portId: port.id,
      ownerType: 'company',
      ownerId: company.id,
    });

    // Membership ended → should not authorise.
    await db.insert(companyMemberships).values({
      companyId: company.id,
      clientId: client.id,
      role: 'director',
      startDate: new Date('2024-01-01'),
      endDate: new Date('2024-12-31'),
    });

    await expect(
      createPending(
        port.id,
        {
          berthId: berth.id,
          clientId: client.id,
          yachtId: yacht.id,
          startDate: new Date(),
          tenureType: 'permanent',
        },
        makeAuditMeta({ portId: port.id }),
      ),
    ).rejects.toThrow(/yacht does not belong/i);
  });

  it('rejects berth from a different port (tenant)', async () => {
    const portA = await makePort();
    const portB = await makePort();
    const berthInB = await makeBerth({ portId: portB.id });
    const clientInA = await makeClient({ portId: portA.id });
    const yachtInA = await makeYacht({
      portId: portA.id,
      ownerType: 'client',
      ownerId: clientInA.id,
    });

    await expect(
      createPending(
        portA.id,
        {
          berthId: berthInB.id,
          clientId: clientInA.id,
          yachtId: yachtInA.id,
          startDate: new Date(),
          tenureType: 'permanent',
        },
        makeAuditMeta({ portId: portA.id }),
      ),
    ).rejects.toThrow(/berth not found/i);
  });

  it('rejects yacht from a different port (tenant)', async () => {
    const portA = await makePort();
    const portB = await makePort();
    const berthInA = await makeBerth({ portId: portA.id });
    const clientInA = await makeClient({ portId: portA.id });
    const clientInB = await makeClient({ portId: portB.id });
    const yachtInB = await makeYacht({
      portId: portB.id,
      ownerType: 'client',
      ownerId: clientInB.id,
    });

    await expect(
      createPending(
        portA.id,
        {
          berthId: berthInA.id,
          clientId: clientInA.id,
          yachtId: yachtInB.id,
          startDate: new Date(),
          tenureType: 'permanent',
        },
        makeAuditMeta({ portId: portA.id }),
      ),
    ).rejects.toThrow(/yacht not found/i);
  });
});

// ─── Lifecycle transitions ───────────────────────────────────────────────────

describe('berth-tenancies.service - lifecycle transitions', () => {
  async function setup() {
    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 reservation = await createPending(
      port.id,
      {
        berthId: berth.id,
        clientId: client.id,
        yachtId: yacht.id,
        startDate: new Date(),
        tenureType: 'permanent',
      },
      makeAuditMeta({ portId: port.id }),
    );
    return { port, berth, client, yacht, reservation };
  }

  it('pending → active (activate)', async () => {
    const { port, reservation } = await setup();
    const activated = await activate(
      reservation.id,
      port.id,
      {},
      makeAuditMeta({ portId: port.id }),
    );
    expect(activated.status).toBe('active');
  });

  it('active → ended (endTenancy)', async () => {
    const { port, reservation } = await setup();
    await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
    const ended = await endTenancy(
      reservation.id,
      port.id,
      { endDate: new Date() },
      makeAuditMeta({ portId: port.id }),
    );
    expect(ended.status).toBe('ended');
    expect(ended.endDate).not.toBeNull();
  });

  it('pending → cancelled (cancel)', async () => {
    const { port, reservation } = await setup();
    const cancelled = await cancel(
      reservation.id,
      port.id,
      { reason: 'client withdrew' },
      makeAuditMeta({ portId: port.id }),
    );
    expect(cancelled.status).toBe('cancelled');
  });

  it('active → cancelled (cancel)', async () => {
    const { port, reservation } = await setup();
    await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
    const cancelled = await cancel(
      reservation.id,
      port.id,
      { reason: 'contract terminated' },
      makeAuditMeta({ portId: port.id }),
    );
    expect(cancelled.status).toBe('cancelled');
  });

  it('rejects ended → active (invalid transition)', async () => {
    const { port, reservation } = await setup();
    await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
    await endTenancy(
      reservation.id,
      port.id,
      { endDate: new Date() },
      makeAuditMeta({ portId: port.id }),
    );
    await expect(
      activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id })),
    ).rejects.toThrow(/invalid transition/i);
  });

  it('rejects cancelled → active (invalid transition)', async () => {
    const { port, reservation } = await setup();
    await cancel(
      reservation.id,
      port.id,
      { reason: 'changed mind' },
      makeAuditMeta({ portId: port.id }),
    );
    await expect(
      activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id })),
    ).rejects.toThrow(/invalid transition/i);
  });

  it('rejects cancel from ended state', async () => {
    const { port, reservation } = await setup();
    await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
    await endTenancy(
      reservation.id,
      port.id,
      { endDate: new Date() },
      makeAuditMeta({ portId: port.id }),
    );
    await expect(
      cancel(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id })),
    ).rejects.toThrow(/invalid transition/i);
  });

  it('rejects endTenancy on a pending reservation', async () => {
    const { port, reservation } = await setup();
    await expect(
      endTenancy(
        reservation.id,
        port.id,
        { endDate: new Date() },
        makeAuditMeta({ portId: port.id }),
      ),
    ).rejects.toThrow(/invalid transition/i);
  });
});

// ─── listTenancies ────────────────────────────────────────────────────────

describe('berth-tenancies.service - listTenancies', () => {
  async function makeTenancyLocal(portId: string, opts?: { berthId?: string }) {
    const berth = opts?.berthId ? { id: opts.berthId } : await makeBerth({ portId });
    const client = await makeClient({ portId });
    const yacht = await makeYacht({ portId, ownerType: 'client', ownerId: client.id });
    return createPending(
      portId,
      {
        berthId: berth.id,
        clientId: client.id,
        yachtId: yacht.id,
        startDate: new Date(),
        tenureType: 'permanent',
      },
      makeAuditMeta({ portId }),
    );
  }

  it('is tenant-scoped', async () => {
    const portA = await makePort();
    const portB = await makePort();
    const resA = await makeTenancyLocal(portA.id);
    await makeTenancyLocal(portB.id);

    const result = await listTenancies(portA.id, {
      page: 1,
      limit: 50,
      order: 'desc',
      includeArchived: false,
    });
    const ids = result.data.map((r) => r.id);
    expect(ids).toContain(resA.id);
    expect(result.data.every((r) => r.portId === portA.id)).toBe(true);
  });

  it('filters by status', async () => {
    const port = await makePort();
    const resPending = await makeTenancyLocal(port.id);
    const resActive = await makeTenancyLocal(port.id);
    await activate(resActive.id, port.id, {}, makeAuditMeta({ portId: port.id }));

    const activeList = await listTenancies(port.id, {
      page: 1,
      limit: 50,
      order: 'desc',
      includeArchived: false,
      status: 'active',
    });
    expect(activeList.data.map((r) => r.id)).toContain(resActive.id);
    expect(activeList.data.map((r) => r.id)).not.toContain(resPending.id);
  });

  it('filters by berthId', async () => {
    const port = await makePort();
    const berth1 = await makeBerth({ portId: port.id });
    const berth2 = await makeBerth({ portId: port.id });

    const client1 = await makeClient({ portId: port.id });
    const yacht1 = await makeYacht({ portId: port.id, ownerType: 'client', ownerId: client1.id });
    const res1 = await createPending(
      port.id,
      { berthId: berth1.id, clientId: client1.id, yachtId: yacht1.id, startDate: new Date() },
      makeAuditMeta({ portId: port.id }),
    );

    const client2 = await makeClient({ portId: port.id });
    const yacht2 = await makeYacht({ portId: port.id, ownerType: 'client', ownerId: client2.id });
    const res2 = await createPending(
      port.id,
      { berthId: berth2.id, clientId: client2.id, yachtId: yacht2.id, startDate: new Date() },
      makeAuditMeta({ portId: port.id }),
    );

    const result = await listTenancies(port.id, {
      page: 1,
      limit: 50,
      order: 'desc',
      includeArchived: false,
      berthId: berth1.id,
    });
    const ids = result.data.map((r) => r.id);
    expect(ids).toContain(res1.id);
    expect(ids).not.toContain(res2.id);
  });
});

// ─── Self-check: DB state is as expected after cancel ────────────────────────

describe('berth-tenancies.service - DB state', () => {
  it('cancel persists status=cancelled in the database', 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 res = await createPending(
      port.id,
      { berthId: berth.id, clientId: client.id, yachtId: yacht.id, startDate: new Date() },
      makeAuditMeta({ portId: port.id }),
    );
    await cancel(res.id, port.id, {}, makeAuditMeta({ portId: port.id }));

    const { berthTenancies } = await import('@/lib/db/schema');
    const [row] = await db.select().from(berthTenancies).where(eq(berthTenancies.id, res.id));
    expect(row!.status).toBe('cancelled');
  });
});
