import type { defineModule as defineOrganizationModule } from "../../organization";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  WarehouseNotFoundError,
  WarehouseNotInactiveError,
  SiteInactiveError,
} from "../lib/errors.generated";
import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/module";

type OrganizationModule = ReturnType<typeof defineOrganizationModule>;
export type OrganizationQueries = OrganizationModule["queries"];

export interface ReactivateWarehouseInput {
  id: string;
}

/**
 * Function: reactivateWarehouse
 *
 * Transitions a warehouse from INACTIVE back to ACTIVE status,
 * allowing it to resume accepting stock movements.
 * The referenced site must still be in ACTIVE status.
 */
export async function run(
  db: Transaction,
  input: ReactivateWarehouseInput,
  ctx: CommandContext,
  organizationQueries: Pick<OrganizationQueries, "getSite">,
) {
  const { id } = input;

  // 1. Check warehouse exists
  const warehouse = await db
    .selectFrom("Warehouse")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!warehouse) {
    return err(new WarehouseNotFoundError(id));
  }

  // 2. Check status is INACTIVE
  if (warehouse.status !== "INACTIVE") {
    return err(new WarehouseNotInactiveError(id));
  }

  // 3. Validate site is still ACTIVE
  const { site } = (await organizationQueries.getSite(db, { id: warehouse.siteId }, ctx)).value;

  if (site?.status !== "ACTIVE") {
    return err(new SiteInactiveError(warehouse.siteId));
  }

  // 4. Update status to ACTIVE
  const reactivatedWarehouse = await db
    .updateTable("Warehouse")
    .set({ status: "ACTIVE", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ warehouse: reactivatedWarehouse });
}
