"""Sequence routes — list, create, update, delete (admin only)."""

from __future__ import annotations

import uuid

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.db import get_db
from app.deps import require_permission
from app.schemas.sequence import SequenceCreate, SequenceUpdate
from app.services import sequence_service

router = APIRouter(prefix="/api/v1/sequences", tags=["sequences"])


@router.get("")
async def list_sequences(
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("sequences:read")),
):
    """List all sequences for the current tenant. Admin only."""
    tenant_id = uuid.UUID(current_user["tenant_id"])


    return await sequence_service.list_sequences(db, tenant_id)


@router.post("", status_code=status.HTTP_201_CREATED)
async def create_sequence(
    body: SequenceCreate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("sequences:write")),
):
    """Create a new sequence. Admin only."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    user_id = uuid.UUID(current_user["user_id"])


    data = body.model_dump()
    return await sequence_service.create_sequence(db, tenant_id, user_id, data)


@router.patch("/{sequence_id}")
async def update_sequence(
    sequence_id: str,
    body: SequenceUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("sequences:write")),
):
    """Update a sequence (name, prefix, padding only). Admin only."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    user_id = uuid.UUID(current_user["user_id"])


    try:
        sid = uuid.UUID(sequence_id)
    except ValueError:
        raise HTTPException(400, detail={"detail": "Invalid sequence_id", "code": "invalid_id"}) from None

    data = body.model_dump(exclude_unset=True)
    result = await sequence_service.update_sequence(db, tenant_id, user_id, sid, data)
    if result is None:
        raise HTTPException(404, detail={"detail": "Sequence not found", "code": "not_found"})
    return result


@router.delete("/{sequence_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_sequence(
    sequence_id: str,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("sequences:write")),
):
    """Delete a sequence (soft-delete). Admin only."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    user_id = uuid.UUID(current_user["user_id"])


    try:
        sid = uuid.UUID(sequence_id)
    except ValueError:
        raise HTTPException(400, detail={"detail": "Invalid sequence_id", "code": "invalid_id"}) from None

    deleted = await sequence_service.delete_sequence(db, tenant_id, user_id, sid)
    if not deleted:
        raise HTTPException(404, detail={"detail": "Sequence not found", "code": "not_found"})
