from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import List, Optional
from datetime import datetime
from odoo import api
from odoo.addons.fastapi.dependencies import odoo_env


# Pydantic схемы
class CompanySchema(BaseModel):
    uuid: str
    name: str
    tax_id: str
    country: str
    country_code: str
    active: bool


class CreateCompanyInput(BaseModel):
    name: str
    tax_id: str
    country_code: str


class UpdateCompanyInput(BaseModel):
    name: Optional[str] = None
    tax_id: Optional[str] = None
    country_code: Optional[str] = None
    active: Optional[bool] = None


router = APIRouter(tags=["companies"])


def build_company_schema(company) -> CompanySchema:
    """Построить схему компании"""
    return CompanySchema(
        uuid=company.uuid,
        name=company.name,
        tax_id=company.tax_id,
        country=company.country_id.name,
        country_code=company.country_id.code,
        active=company.active
    )


@router.get("/companies", response_model=List[CompanySchema])
async def get_companies(
    active_only: bool = True,
    country_code: Optional[str] = None,
    env: api.Environment = Depends(odoo_env)
):
    """Получить список компаний с фильтрами"""
    try:
        domain = []
        
        if active_only:
            domain.append(('active', '=', True))
            
        if country_code:
            domain.append(('country_id.code', '=', country_code.upper()))
        
        companies = env['marketplace.company'].search(domain)
        
        return [build_company_schema(company) for company in companies]
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error fetching companies: {str(e)}")


@router.get("/companies/{company_uuid}", response_model=CompanySchema)
async def get_company_by_uuid(company_uuid: str, env: api.Environment = Depends(odoo_env)):
    """Получить компанию по UUID"""
    try:
        company = env['marketplace.company'].search([('uuid', '=', company_uuid)], limit=1)
        
        if not company:
            raise HTTPException(status_code=404, detail="Company not found")
        
        return build_company_schema(company)
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error fetching company: {str(e)}")


@router.post("/companies", response_model=CompanySchema)
async def create_company(company_input: CreateCompanyInput, env: api.Environment = Depends(odoo_env)):
    """Создать новую компанию"""
    try:
        # Проверяем уникальность tax_id
        existing_company = env['marketplace.company'].search([('tax_id', '=', company_input.tax_id)], limit=1)
        if existing_company:
            raise HTTPException(status_code=400, detail=f"Company with tax_id {company_input.tax_id} already exists")
        
        # Находим страну по коду
        country = env['res.country'].search([('code', '=', company_input.country_code.upper())], limit=1)
        if not country:
            raise HTTPException(status_code=400, detail=f"Country with code {company_input.country_code} not found")
        
        # Создаем компанию
        company = env['marketplace.company'].create({
            'name': company_input.name,
            'tax_id': company_input.tax_id,
            'country_id': country.id,
        })
        
        return build_company_schema(company)
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error creating company: {str(e)}")


@router.patch("/companies/{company_uuid}", response_model=CompanySchema)
async def update_company(
    company_uuid: str, 
    company_input: UpdateCompanyInput, 
    env: api.Environment = Depends(odoo_env)
):
    """Обновить компанию"""
    try:
        company = env['marketplace.company'].search([('uuid', '=', company_uuid)], limit=1)
        
        if not company:
            raise HTTPException(status_code=404, detail="Company not found")
        
        # Подготавливаем данные для обновления
        update_data = {}
        for field, value in company_input.dict(exclude_unset=True).items():
            if value is not None:
                update_data[field] = value
        
        if update_data:
            company.write(update_data)
        
        return build_company_schema(company)
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error updating company: {str(e)}")


@router.delete("/companies/{company_uuid}")
async def delete_company(company_uuid: str, env: api.Environment = Depends(odoo_env)):
    """Удалить компанию (деактивировать)"""
    try:
        company = env['marketplace.company'].search([('uuid', '=', company_uuid)], limit=1)
        
        if not company:
            raise HTTPException(status_code=404, detail="Company not found")
        
        # Деактивируем вместо удаления
        company.write({'active': False})
        
        return {"message": "Company deactivated successfully"}
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error deleting company: {str(e)}")




@router.get("/companies/by-country/{country_code}", response_model=List[CompanySchema])
async def get_companies_by_country_code(country_code: str, env: api.Environment = Depends(odoo_env)):
    """Получить компании по стране"""
    try:
        companies = env['marketplace.company'].search([
            ('country_id.code', '=', country_code.upper()),
            ('active', '=', True)
        ])
        
        return [build_company_schema(company) for company in companies]
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error fetching companies by country: {str(e)}")