# Category / Subcategory Specification

## Goal

Allow unlimited-depth category hierarchy while preserving current products and URLs.

The first useful level is:
Category -> Subcategory
but the data model should support parent/child recursively unless the existing system makes that unsafe.

## Data model

If categories already exist, extend them instead of creating a parallel system.

Preferred field:
- `parent_id` nullable self-reference

Additional useful fields if missing:
- name
- slug
- description
- image
- sort_order
- is_active
- seo_title
- seo_description
- canonical_url
- robots_index
- robots_follow

Use foreign key:
`parent_id -> categories.id`
with a safe delete strategy. Do not cascade-delete a category tree containing products unless the current business logic explicitly requires it.

## Business rules

- root category: `parent_id = null`
- child category: `parent_id = another category id`
- category cannot be its own parent
- category cannot create a cycle
- slug uniqueness must follow the public URL strategy
- inactive category behavior must be explicit
- deleting/moving a category must not silently lose products

## Product relationship

Inspect existing product-category relationship.

If products currently have one category:
- preserve compatibility
- support a primary category
- only introduce many-to-many if the application actually needs it

If many-to-many already exists:
- preserve it
- define primary category behavior for breadcrumbs/canonical URL

## Admin UI

Category form:
- name
- parent category dropdown/tree
- slug
- description
- image
- active
- sort order
- SEO fields

Category list:
- tree view or nested indentation
- search
- filter active/inactive
- reorder where existing UI supports it

Prevent selecting a descendant as a parent during edit.

## Frontend

Category page should show:
- breadcrumb tree
- title/intro
- child categories
- products
- pagination where needed

Parent category should link to child categories.

Child category should link to parent.

## URL strategy

Do not force a breaking URL change.

Possible hierarchy URL:
`/products/{category-slug}`
or
`/products/{parent}/{child}`

Choose based on current routing and migration cost.

If changing:
- 301 old URL
- update canonical
- update sitemap
- update internal links

## Tests

Test:
- create root category
- create child
- reject self-parent
- reject cycle
- move child
- delete safely
- product/category resolution
- breadcrumb correctness
- canonical correctness
