from fastapi import APIRouter, HTTPException, status, Depends
from sqlalchemy.orm import Session
from typing import List
from app.schemas import Address as AddressSchema, AddressCreate, AddressUpdate
from app.models import Address as AddressModel
from app.dependencies import get_db

router = APIRouter()


@router.get("/", response_model=List[AddressSchema])
async def get_return_addresses(db: Session = Depends(get_db)):
    return db.query(AddressModel).all()


@router.post("/", response_model=AddressSchema, status_code=status.HTTP_201_CREATED)
async def create_return_address(address: AddressCreate, db: Session = Depends(get_db)):
    if db.query(AddressModel).filter(AddressModel.city == address.city).first():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Address in this city already exists.",
        )

    db_address = AddressModel(
        street=address.street,
        city=address.city,
        zipcode=address.zipcode,
        country=address.country,
    )

    db.add(db_address)
    db.commit()
    db.refresh(db_address)
    return db_address


@router.put("/{address_id}", response_model=AddressSchema)
async def update_return_address(
    address_id: int, address: AddressUpdate, db: Session = Depends(get_db)
):
    db_address = db.query(AddressModel).filter(AddressModel.id == address_id).first()
    if not db_address:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Address not found."
        )
    for key, value in address.dict(exclude_unset=True).items():
        setattr(db_address, key, value)
    db.commit()
    db.refresh(db_address)
    return db_address


@router.delete("/{address_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_return_address(address_id: int, db: Session = Depends(get_db)):
    db_address = db.query(AddressModel).filter(AddressModel.id == address_id).first()
    if not db_address:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Address not found."
        )
    db.delete(db_address)
    db.commit()
    return
