-- Asset Sub-Categories master + assets.asset_subcategory_id

CREATE TABLE IF NOT EXISTS asset_subcategories (
  id                BIGSERIAL PRIMARY KEY,
  asset_category_id BIGINT NOT NULL REFERENCES asset_categories (id),
  code              VARCHAR(30) NOT NULL UNIQUE,
  name              VARCHAR(150) NOT NULL,
  is_active         BOOLEAN NOT NULL DEFAULT true,
  created_by        BIGINT,
  updated_by        BIGINT,
  created_at        TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at        TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  deleted_at        TIMESTAMPTZ
);

CREATE INDEX IF NOT EXISTS idx_asset_subcategories_category_id
  ON asset_subcategories (asset_category_id);

ALTER TABLE assets
  ADD COLUMN IF NOT EXISTS asset_subcategory_id BIGINT;

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'assets_asset_subcategory_id_fkey'
  ) THEN
    ALTER TABLE assets
      ADD CONSTRAINT assets_asset_subcategory_id_fkey
      FOREIGN KEY (asset_subcategory_id)
      REFERENCES asset_subcategories (id);
  END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_assets_subcategory_id
  ON assets (asset_subcategory_id);

COMMENT ON TABLE asset_subcategories IS 'Asset sub-categories under asset_categories';
COMMENT ON COLUMN assets.asset_subcategory_id IS 'Required for new assets via API; nullable for legacy rows';
