/**
 * Task 2 - ensureSystemRoots (TDD).
 * Task 3 - ensureEntityFolder (TDD).
 *
 * Fixture convention: makePort from helpers/factories (async DB insert);
 * TEST_USER_ID resolved once via beforeAll from a seeded user - same pattern
 * as document-folders-crud.test.ts and alerts-tenant-isolation.test.ts.
 */

import { describe, it, expect, beforeAll, beforeEach } from 'vitest';
import { and, eq } from 'drizzle-orm';

import { db } from '@/lib/db';
import { documentFolders } from '@/lib/db/schema/documents';
import { clients } from '@/lib/db/schema/clients';
import { user } from '@/lib/db/schema/users';
import { ensureSystemRoots, ensureEntityFolder } from '@/lib/services/document-folders.service';
import { makePort } from '../helpers/factories';

let TEST_USER_ID = '';

beforeAll(async () => {
  const [u] = await db.select({ id: user.id }).from(user).limit(1);
  if (!u) throw new Error('No user available; run pnpm db:seed first');
  TEST_USER_ID = u.id;
});

describe('document-folders service · ensureSystemRoots', () => {
  let portId: string;

  beforeEach(async () => {
    const port = await makePort();
    portId = port.id;
    await db.delete(documentFolders).where(eq(documentFolders.portId, portId));
  });

  it('creates Clients, Companies, and Yachts root folders with system_managed=true', async () => {
    await ensureSystemRoots(portId, TEST_USER_ID);
    const rows = await db
      .select()
      .from(documentFolders)
      .where(and(eq(documentFolders.portId, portId), eq(documentFolders.entityType, 'root')));
    expect(rows.map((r) => r.name).sort()).toEqual(['Clients', 'Companies', 'Yachts']);
    for (const r of rows) {
      expect(r.systemManaged).toBe(true);
      expect(r.parentId).toBeNull();
      expect(r.entityId).toBeNull();
    }
  });

  it('is idempotent - second call does not create duplicates', async () => {
    await ensureSystemRoots(portId, TEST_USER_ID);
    await ensureSystemRoots(portId, TEST_USER_ID);
    const rows = await db
      .select()
      .from(documentFolders)
      .where(and(eq(documentFolders.portId, portId), eq(documentFolders.entityType, 'root')));
    expect(rows).toHaveLength(3);
  });

  it('returns the three root rows in a stable order (Clients, Companies, Yachts)', async () => {
    const roots = await ensureSystemRoots(portId, TEST_USER_ID);
    expect(roots.map((r) => r.name)).toEqual(['Clients', 'Companies', 'Yachts']);
  });
});

describe('document-folders service · ensureEntityFolder', () => {
  let portId: string;
  let clientId: string;
  let rootId: string;

  beforeEach(async () => {
    const port = await makePort();
    portId = port.id;
    await db.delete(documentFolders).where(eq(documentFolders.portId, portId));
    const roots = await ensureSystemRoots(portId, TEST_USER_ID);
    rootId = roots.find((r) => r.name === 'Clients')!.id;

    const [client] = await db
      .insert(clients)
      .values({
        portId,
        fullName: `Smith, John ${crypto.randomUUID().slice(0, 8)}`,
      })
      .returning();
    clientId = client!.id;
  });

  it('creates a subfolder under the matching system root with system_managed=true', async () => {
    const folder = await ensureEntityFolder(portId, 'client', clientId, TEST_USER_ID);
    expect(folder.systemManaged).toBe(true);
    expect(folder.entityType).toBe('client');
    expect(folder.entityId).toBe(clientId);
    expect(folder.parentId).toBe(rootId);
    // name is the client's fullName verbatim
    const [row] = await db.select().from(clients).where(eq(clients.id, clientId));
    expect(folder.name).toBe(row!.fullName);
  });

  it('is idempotent - returns the same row on second call', async () => {
    const a = await ensureEntityFolder(portId, 'client', clientId, TEST_USER_ID);
    const b = await ensureEntityFolder(portId, 'client', clientId, TEST_USER_ID);
    expect(a.id).toBe(b.id);
    const all = await db
      .select()
      .from(documentFolders)
      .where(and(eq(documentFolders.entityType, 'client'), eq(documentFolders.entityId, clientId)));
    expect(all).toHaveLength(1);
  });

  it('appends a numeric suffix on name collision with an existing folder', async () => {
    // Insert a second client with the exact same fullName as the first.
    const [firstClient] = await db.select().from(clients).where(eq(clients.id, clientId));
    const sharedName = firstClient!.fullName;

    const [collidingClient] = await db
      .insert(clients)
      .values({
        portId,
        fullName: sharedName,
      })
      .returning();

    await ensureEntityFolder(portId, 'client', clientId, TEST_USER_ID);
    const second = await ensureEntityFolder(portId, 'client', collidingClient!.id, TEST_USER_ID);
    expect(second.name).toBe(`${sharedName} (2)`);
  });

  it('rejects unknown entity types', async () => {
    await expect(
      // @ts-expect-error -- runtime check
      ensureEntityFolder(portId, 'boat', clientId, TEST_USER_ID),
    ).rejects.toThrow(/entity type/i);
  });
});

import {
  deleteFolderSoftRescue,
  moveFolder,
  renameFolder,
  syncEntityFolderName,
  applyEntityArchivedSuffix,
  applyEntityRestoredSuffix,
  demoteSystemFolderOnEntityDelete,
} from '@/lib/services/document-folders.service';

describe('document-folders service · system folder protection', () => {
  let portId: string;
  let rootId: string;

  beforeEach(async () => {
    const port = await makePort();
    portId = port.id;
    await db.delete(documentFolders).where(eq(documentFolders.portId, portId));
    const roots = await ensureSystemRoots(portId, TEST_USER_ID);
    rootId = roots.find((r) => r.name === 'Clients')!.id;
  });

  it('rejects rename of a system-managed root', async () => {
    await expect(renameFolder(portId, rootId, 'Customers', TEST_USER_ID)).rejects.toThrow(
      /system folder/i,
    );
  });

  it('rejects move of a system-managed root', async () => {
    const other = await ensureSystemRoots(portId, TEST_USER_ID);
    const companies = other.find((r) => r.name === 'Companies')!;
    await expect(moveFolder(portId, rootId, companies.id, TEST_USER_ID)).rejects.toThrow(
      /system folder/i,
    );
  });

  it('rejects delete of a system-managed root', async () => {
    await expect(deleteFolderSoftRescue(portId, rootId, TEST_USER_ID)).rejects.toThrow(
      /system folder/i,
    );
  });

  it('allows rename/delete of a user folder under a system root', async () => {
    const user = await db
      .insert(documentFolders)
      .values({
        portId,
        parentId: rootId,
        name: 'Templates',
        systemManaged: false,
        createdBy: TEST_USER_ID,
      })
      .returning();
    await expect(
      renameFolder(portId, user[0]!.id, 'My Templates', TEST_USER_ID),
    ).resolves.toBeDefined();
  });
});

describe('document-folders service · syncEntityFolderName', () => {
  let portId: string;
  let clientId: string;

  beforeEach(async () => {
    const port = await makePort();
    portId = port.id;
    await db.delete(documentFolders).where(eq(documentFolders.portId, portId));
    await ensureSystemRoots(portId, TEST_USER_ID);
    const originalFullName = `John Smith ${crypto.randomUUID().slice(0, 6)}`;
    const [client] = await db
      .insert(clients)
      .values({
        portId,
        fullName: originalFullName,
      })
      .returning();
    clientId = client!.id;
    await ensureEntityFolder(portId, 'client', clientId, TEST_USER_ID);
  });

  it('renames the entity subfolder when the entity is renamed', async () => {
    const newName = `Jonathan Smith ${crypto.randomUUID().slice(0, 6)}`;
    await db.update(clients).set({ fullName: newName }).where(eq(clients.id, clientId));
    await syncEntityFolderName(portId, 'client', clientId, TEST_USER_ID);
    const folder = await db.query.documentFolders.findFirst({
      where: and(eq(documentFolders.entityType, 'client'), eq(documentFolders.entityId, clientId)),
    });
    expect(folder?.name).toBe(newName);
  });

  it('is a no-op when the folder does not exist (lazy creation)', async () => {
    const otherPort = await makePort();
    await ensureSystemRoots(otherPort.id, TEST_USER_ID);
    const [otherClient] = await db
      .insert(clients)
      .values({ portId: otherPort.id, fullName: `Jane Doe ${crypto.randomUUID().slice(0, 6)}` })
      .returning();
    // No folder created. Sync should not throw.
    await expect(
      syncEntityFolderName(otherPort.id, 'client', otherClient!.id, TEST_USER_ID),
    ).resolves.toBeUndefined();
  });

  it('appends numeric suffix on rename collision (target name already taken)', async () => {
    const sharedName = `Jane Smith ${crypto.randomUUID().slice(0, 6)}`;
    const [collider] = await db
      .insert(clients)
      .values({ portId, fullName: sharedName })
      .returning();
    await ensureEntityFolder(portId, 'client', collider!.id, TEST_USER_ID);

    // Rename John → same as collider.
    await db.update(clients).set({ fullName: sharedName }).where(eq(clients.id, clientId));
    await syncEntityFolderName(portId, 'client', clientId, TEST_USER_ID);

    const folder = await db.query.documentFolders.findFirst({
      where: and(eq(documentFolders.entityType, 'client'), eq(documentFolders.entityId, clientId)),
    });
    expect(folder?.name).toBe(`${sharedName} (2)`);
  });
});

describe('document-folders service · archive lifecycle', () => {
  let portId: string;
  let clientId: string;
  let clientName: string;

  beforeEach(async () => {
    const port = await makePort();
    portId = port.id;
    await db.delete(documentFolders).where(eq(documentFolders.portId, portId));
    await ensureSystemRoots(portId, TEST_USER_ID);
    clientName = `John Smith ${crypto.randomUUID().slice(0, 6)}`;
    const [client] = await db.insert(clients).values({ portId, fullName: clientName }).returning();
    clientId = client!.id;
    await ensureEntityFolder(portId, 'client', clientId, TEST_USER_ID);
  });

  it('appends (archived) suffix and stamps archived_at on archive', async () => {
    await applyEntityArchivedSuffix(portId, 'client', clientId);
    const folder = await db.query.documentFolders.findFirst({
      where: and(eq(documentFolders.entityType, 'client'), eq(documentFolders.entityId, clientId)),
    });
    expect(folder?.name).toBe(`${clientName} (archived)`);
    expect(folder?.archivedAt).toBeInstanceOf(Date);
    expect(folder?.systemManaged).toBe(true);
  });

  it('is idempotent on archive - second call does not double-append', async () => {
    await applyEntityArchivedSuffix(portId, 'client', clientId);
    await applyEntityArchivedSuffix(portId, 'client', clientId);
    const folder = await db.query.documentFolders.findFirst({
      where: and(eq(documentFolders.entityType, 'client'), eq(documentFolders.entityId, clientId)),
    });
    expect(folder?.name).toBe(`${clientName} (archived)`);
  });

  it('removes (archived) suffix and clears archived_at on restore', async () => {
    await applyEntityArchivedSuffix(portId, 'client', clientId);
    await applyEntityRestoredSuffix(portId, 'client', clientId);
    const folder = await db.query.documentFolders.findFirst({
      where: and(eq(documentFolders.entityType, 'client'), eq(documentFolders.entityId, clientId)),
    });
    expect(folder?.name).toBe(clientName);
    expect(folder?.archivedAt).toBeNull();
  });

  it('appends (deleted) and flips system_managed=false on hard-delete', async () => {
    await demoteSystemFolderOnEntityDelete(portId, 'client', clientId);
    // After demotion, entityType + entityId are cleared, so we look up by name.
    const folder = await db.query.documentFolders.findFirst({
      where: and(
        eq(documentFolders.portId, portId),
        eq(documentFolders.name, `${clientName} (deleted)`),
      ),
    });
    expect(folder?.systemManaged).toBe(false);
    expect(folder?.entityType).toBeNull();
    expect(folder?.entityId).toBeNull();
  });

  it('is a no-op when the folder does not exist', async () => {
    const otherPort = await makePort();
    await ensureSystemRoots(otherPort.id, TEST_USER_ID);
    const [other] = await db
      .insert(clients)
      .values({ portId: otherPort.id, fullName: `Lone Wolf ${crypto.randomUUID().slice(0, 6)}` })
      .returning();
    await expect(
      applyEntityArchivedSuffix(otherPort.id, 'client', other!.id),
    ).resolves.toBeUndefined();
  });
});
