from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy import text
from pydantic import BaseModel
from ..database import get_db
from ..auth.middleware import get_current_user

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

class BrandUpdate(BaseModel):
    brand: str

class UserRequirementUpdate(BaseModel):
    user_requirement: str

@router.patch("/{material_id}/brand")
async def update_material_brand(
    material_id: int,
    brand_data: BrandUpdate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """자재의 브랜드 정보를 업데이트합니다."""
    try:
        # 자재 존재 여부 확인
        result = db.execute(
            text("SELECT id FROM materials WHERE id = :material_id"),
            {"material_id": material_id}
        )
        material = result.fetchone()
        
        if not material:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="자재를 찾을 수 없습니다."
            )
        
        # 브랜드 업데이트
        db.execute(
            text("""
                UPDATE materials 
                SET brand = :brand, 
                    updated_by = :updated_by
                WHERE id = :material_id
            """),
            {
                "brand": brand_data.brand.strip(),
                "updated_by": current_user.get("username", "unknown"),
                "material_id": material_id
            }
        )
        
        db.commit()
        
        return {
            "success": True,
            "message": "브랜드가 성공적으로 업데이트되었습니다.",
            "material_id": material_id,
            "brand": brand_data.brand.strip()
        }
        
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"브랜드 업데이트 실패: {str(e)}"
        )

@router.patch("/{material_id}/user-requirement")
async def update_material_user_requirement(
    material_id: int,
    requirement_data: UserRequirementUpdate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """자재의 사용자 요구사항을 업데이트합니다."""
    try:
        # 자재 존재 여부 확인
        result = db.execute(
            text("SELECT id FROM materials WHERE id = :material_id"),
            {"material_id": material_id}
        )
        material = result.fetchone()
        
        if not material:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="자재를 찾을 수 없습니다."
            )
        
        # 사용자 요구사항 업데이트
        db.execute(
            text("""
                UPDATE materials 
                SET user_requirement = :user_requirement, 
                    updated_by = :updated_by
                WHERE id = :material_id
            """),
            {
                "user_requirement": requirement_data.user_requirement.strip(),
                "updated_by": current_user.get("username", "unknown"),
                "material_id": material_id
            }
        )
        
        db.commit()
        
        return {
            "success": True,
            "message": "사용자 요구사항이 성공적으로 업데이트되었습니다.",
            "material_id": material_id,
            "user_requirement": requirement_data.user_requirement.strip()
        }
        
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"사용자 요구사항 업데이트 실패: {str(e)}"
        )

@router.get("/{material_id}")
async def get_material(
    material_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """자재 정보를 조회합니다."""
    try:
        result = db.execute(
            text("""
                SELECT id, original_description, classified_category, 
                       brand, user_requirement, created_at, updated_by
                FROM materials 
                WHERE id = :material_id
            """),
            {"material_id": material_id}
        )
        material = result.fetchone()
        
        if not material:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="자재를 찾을 수 없습니다."
            )
        
        return {
            "id": material.id,
            "original_description": material.original_description,
            "classified_category": material.classified_category,
            "brand": material.brand,
            "user_requirement": material.user_requirement,
            "created_at": material.created_at,
            "updated_by": material.updated_by
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"자재 조회 실패: {str(e)}"
        )
