import { eq } from 'drizzle-orm';

import { db } from '@/lib/db';
import { ports } from '@/lib/db/schema';
import type { PortSettings } from '@/lib/db/schema/ports';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { ConflictError, NotFoundError } from '@/lib/errors';
import { logger } from '@/lib/logger';
import { emitToRoom } from '@/lib/socket/server';
import type { CreatePortInput, UpdatePortInput } from '@/lib/validators/ports';
import { ensureSystemRoots } from '@/lib/services/document-folders.service';

export async function listPorts() {
  // Creation order (oldest first), not alphabetical: the first-seeded port
  // is the primary one (Port Nimara), so it leads the switcher and is the
  // default a super-admin lands on. Alphabetical put "Port Amador" ahead of
  // "Port Nimara". Name is a stable tiebreaker for same-instant inserts.
  return db.select().from(ports).orderBy(ports.createdAt, ports.name);
}

export async function getPort(id: string) {
  const port = await db.query.ports.findFirst({
    where: eq(ports.id, id),
  });
  if (!port) throw new NotFoundError('Port');
  return port;
}

export async function createPort(data: CreatePortInput, meta: AuditMeta) {
  const existing = await db.query.ports.findFirst({
    where: eq(ports.slug, data.slug),
  });
  if (existing) {
    throw new ConflictError(`A port with slug "${data.slug}" already exists`);
  }

  const [port] = await db
    .insert(ports)
    .values({
      name: data.name,
      slug: data.slug,
      logoUrl: data.logoUrl ?? null,
      primaryColor: data.primaryColor ?? null,
      defaultCurrency: data.defaultCurrency,
      timezone: data.timezone,
    })
    .returning();

  // Non-fatal if this throws: ensureSystemRoots is re-runnable (any
  // subsequent admin action self-heals via `ensureEntityFolder`'s
  // fallback, and `scripts/backfill-document-folders.ts` covers
  // orphaned ports). Swallow + log instead of propagating, so the
  // operator doesn't see a 500 from `createPort` against an already-
  // committed port row - they'd retry and hit a 409 slug-exists.
  try {
    await ensureSystemRoots(port!.id, meta.userId);
  } catch (err) {
    logger.warn(
      { portId: port!.id, err },
      'ensureSystemRoots failed after port create - port row is live; system folders will be created on first admin action.',
    );
  }

  void createAuditLog({
    userId: meta.userId,
    portId: meta.portId,
    action: 'create',
    entityType: 'port',
    entityId: port!.id,
    newValue: { name: port!.name, slug: port!.slug },
    ipAddress: meta.ipAddress,
    userAgent: meta.userAgent,
  });

  return port!;
}

export async function updatePort(id: string, data: UpdatePortInput, meta: AuditMeta) {
  const port = await db.query.ports.findFirst({
    where: eq(ports.id, id),
  });
  if (!port) throw new NotFoundError('Port');

  if (data.slug && data.slug !== port.slug) {
    const conflict = await db.query.ports.findFirst({
      where: eq(ports.slug, data.slug),
    });
    if (conflict) {
      throw new ConflictError(`A port with slug "${data.slug}" already exists`);
    }
  }

  const updates: Record<string, unknown> = { updatedAt: new Date() };
  if (data.name !== undefined) updates.name = data.name;
  if (data.slug !== undefined) updates.slug = data.slug;
  if (data.logoUrl !== undefined) updates.logoUrl = data.logoUrl;
  if (data.primaryColor !== undefined) updates.primaryColor = data.primaryColor;
  if (data.defaultCurrency !== undefined) updates.defaultCurrency = data.defaultCurrency;
  if (data.timezone !== undefined) updates.timezone = data.timezone;
  if (data.isActive !== undefined) updates.isActive = data.isActive;
  if (data.settings !== undefined) updates.settings = data.settings as PortSettings;

  const [updated] = await db.update(ports).set(updates).where(eq(ports.id, id)).returning();

  void createAuditLog({
    userId: meta.userId,
    portId: meta.portId,
    action: 'update',
    entityType: 'port',
    entityId: id,
    oldValue: { name: port.name, slug: port.slug, isActive: port.isActive },
    newValue: { name: updated!.name, slug: updated!.slug, isActive: updated!.isActive },
    ipAddress: meta.ipAddress,
    userAgent: meta.userAgent,
  });

  emitToRoom(`port:${id}`, 'system:alert', {
    alertType: 'port:updated',
    message: `Port "${updated!.name}" updated`,
    severity: 'info',
  });

  return updated!;
}
