BEGIN;

INSERT INTO fifo_stock_v2_traits(
    source_table,
    lane,
    date_table,
    date_join_left_col,
    date_join_right_col,
    date_column,
    fallback_date_column,
    sort_priority,
    id_column,
    is_active
)
VALUES
    ('project_flock_populations', 'STOCKABLE', 'project_chickins', 'project_chickin_id', 'id', 'chick_in_date', 'created_at', 55, 'id', TRUE)
ON CONFLICT (source_table, lane) DO UPDATE
SET
    date_table = EXCLUDED.date_table,
    date_join_left_col = EXCLUDED.date_join_left_col,
    date_join_right_col = EXCLUDED.date_join_right_col,
    date_column = EXCLUDED.date_column,
    fallback_date_column = EXCLUDED.fallback_date_column,
    sort_priority = EXCLUDED.sort_priority,
    id_column = EXCLUDED.id_column,
    is_active = TRUE;

INSERT INTO fifo_stock_v2_route_rules(
    flag_group_code,
    lane,
    function_code,
    source_table,
    source_id_column,
    product_warehouse_col,
    quantity_col,
    used_quantity_col,
    pending_quantity_col,
    scope_sql,
    legacy_type_key,
    allow_pending_default,
    is_active
)
VALUES
    ('AYAM', 'STOCKABLE', 'POPULATION_IN', 'project_flock_populations', 'id', 'product_warehouse_id', 'total_qty', 'total_used_qty', NULL, NULL, 'PROJECT_FLOCK_POPULATION', TRUE, TRUE)
ON CONFLICT (flag_group_code, lane, function_code, source_table) DO UPDATE
SET
    source_id_column = EXCLUDED.source_id_column,
    product_warehouse_col = EXCLUDED.product_warehouse_col,
    quantity_col = EXCLUDED.quantity_col,
    used_quantity_col = EXCLUDED.used_quantity_col,
    pending_quantity_col = EXCLUDED.pending_quantity_col,
    scope_sql = EXCLUDED.scope_sql,
    legacy_type_key = EXCLUDED.legacy_type_key,
    allow_pending_default = EXCLUDED.allow_pending_default,
    is_active = TRUE,
    updated_at = NOW();

UPDATE project_flock_populations p
SET total_used_qty = COALESCE(a.used, 0)
FROM (
    SELECT stockable_id, SUM(qty) AS used
    FROM stock_allocations
    WHERE stockable_type = 'PROJECT_FLOCK_POPULATION'
      AND status = 'ACTIVE'
      AND allocation_purpose = 'CONSUME'
    GROUP BY stockable_id
) a
WHERE p.id = a.stockable_id;

UPDATE project_flock_populations p
SET total_used_qty = 0
WHERE NOT EXISTS (
    SELECT 1
    FROM stock_allocations sa
    WHERE sa.stockable_type = 'PROJECT_FLOCK_POPULATION'
      AND sa.status = 'ACTIVE'
      AND sa.allocation_purpose = 'CONSUME'
      AND sa.stockable_id = p.id
);

COMMIT;
