import os
import shutil
import pandas as pd
from fastapi import File, UploadFile
from fastapi.responses import FileResponse, JSONResponse
from sqlalchemy.orm import Session

from app.api.corporate_store.service import UPLOAD_DIR
from app.dependency.authantication import JWTPayloadSchema
from app.models.main.student import TblStudent

class InventoryExcelService:
    def __init__(self, db:Session, token:JWTPayloadSchema):
        self.db = db
        self.token = token
        
    async def download_inventory_excel(self):
        file_path = "files/5Sample_Inventory Policies.xlsx"
        return FileResponse(
            path = file_path,
            media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            filename = "5Sample_Inventory Policies.xlsx"
        )
    
    UPLOAD_DIR = "uploaded_files"
    os.makedirs(UPLOAD_DIR, exist_ok=True)
    
    async def upload_inventory_excel(self, file:UploadFile = File(...)):
        student_id = getattr(self.token, "student_id", None)
        
        if student_id is None:
            return JSONResponse(status_code=404, content={"error": "student_id missing in token."})
        student = self.db.query(TblStudent).filter(TblStudent.student_id == student_id).first()
        if not student:
            return JSONResponse(status_code=404, content={"error": "Student not found."})
        
        if not student.group:
            return JSONResponse(status_code=404, content={"error": "Group not assigned to this student."})
        
        group = student.group
        
        filename = file.filename or "uploaded_file.xlsx"
        file_location = os.path.join(UPLOAD_DIR, filename)
        with open(file_location, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
            
        df = pd.read_excel(file_location)
        
        group.inventory_managemannt_excel = file_location
        self.db.commit()
        
        return JSONResponse(content={
            "message": "File uploaded and group updated successfully!",
            "group_id": group.group_id,
            "filename": file_location
        })