from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session
from utils.utils import get_db
from . import handler
from .schema import SubmissionCreate, SubmissionUpdate, SubmissionResponse, SubmissionListResponse

router = APIRouter(prefix="/submissions", tags=["Submissions"])


@router.post(
    "/",
    response_model=SubmissionResponse,
    status_code=status.HTTP_201_CREATED,
    summary="Create New Submission",
    description="Creates a new form submission with name and email. Validates that name is not empty after trimming and email matches valid format. Returns the created submission with generated ID and timestamps.",
)
def create_submission_route(data: SubmissionCreate, db: Session = Depends(get_db)):
    return handler.create_submission(db, data)


@router.get(
    "/",
    response_model=SubmissionListResponse,
    summary="List All Submissions",
    description="Returns a paginated list of all submissions ordered by creation date descending (newest first). Supports limit and offset parameters for pagination.",
)
def list_submissions_route(
    limit: int = Query(20, ge=1),
    offset: int = Query(0, ge=0),
    db: Session = Depends(get_db),
):
    return handler.list_submissions(db, limit, offset)


@router.get(
    "/{submission_id}",
    response_model=SubmissionResponse,
    summary="Get Submission By ID",
    description="Retrieves a single submission by its unique identifier. Returns 404 if the submission does not exist.",
)
def get_submission_route(submission_id: str, db: Session = Depends(get_db)):
    return handler.get_submission(db, submission_id)


@router.patch(
    "/{submission_id}",
    response_model=SubmissionResponse,
    summary="Update Submission",
    description="Updates an existing submission. Only provided fields are updated. Validates name and email format if provided. Returns 404 if submission not found.",
)
def update_submission_route(
    submission_id: str,
    data: SubmissionUpdate,
    db: Session = Depends(get_db),
):
    return handler.update_submission(db, submission_id, data)


@router.delete(
    "/{submission_id}",
    status_code=status.HTTP_200_OK,
    summary="Delete Submission",
    description="Deletes a submission by ID. Returns 404 if the submission does not exist. Returns success message on successful deletion.",
)
def delete_submission_route(submission_id: str, db: Session = Depends(get_db)):
    return handler.delete_submission(db, submission_id)