# app/api/v1/endpoints/auth.py
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, EmailStr, Field, validator
from sqlalchemy.orm import Session
from datetime import timedelta
import logging

from app.api.deps import get_db
from app.services.auth_service import AuthService

router = APIRouter()
logger = logging.getLogger('adimsayar')

class RefreshTokenRequest(BaseModel):
    refresh_token: str

@router.post("/refresh-token")
def refresh_token_endpoint(refresh_req: RefreshTokenRequest):
    return AuthService.refresh_token(refresh_req.refresh_token)

class ForgotPasswordRequest(BaseModel):
    email: EmailStr

@router.post("/forgot-password")
def forgot_password(req: ForgotPasswordRequest, db: Session = Depends(get_db)):
    return AuthService.forgot_password(db, req.email)

class VerifyResetCodeRequest(BaseModel):
    email: EmailStr
    reset_code: str

@router.post("/verify-reset-code")
def verify_reset_code(req: VerifyResetCodeRequest, db: Session = Depends(get_db)):
    return AuthService.verify_reset_code(db, req.email, req.reset_code)

class ChangePasswordRequest(BaseModel):
    email: EmailStr
    reset_code: str
    new_password: str = Field(..., min_length=6)
    confirm_password: str = Field(..., min_length=6)

    @validator('confirm_password')
    def passwords_must_match(cls, v, values, **kwargs):
        if 'new_password' in values and v != values['new_password']:
            raise ValueError('New password and confirmation do not match')
        return v

@router.post("/change-password")
def change_password(req: ChangePasswordRequest, db: Session = Depends(get_db)):
    return AuthService.change_password(db, req.email, req.reset_code, req.new_password)