from uuid import UUID
from app.modules.takeoff.domain.entities import CADTakeoff

class TakeoffRepository:
    def __init__(self, conn):
        self._conn = conn

    def ensure_schema(self):
        with self._conn.cursor() as cur:
            cur.execute("""
                CREATE SCHEMA IF NOT EXISTS takeoff;
                CREATE TABLE IF NOT EXISTS takeoff.cad_takeoffs (
                    id UUID PRIMARY KEY,
                    project_id UUID NOT NULL,
                    drawing_reference TEXT NOT NULL,
                    material_code TEXT NOT NULL,
                    quantity NUMERIC(18, 4) NOT NULL,
                    unit TEXT NOT NULL,
                    created_at TIMESTAMP WITH TIME ZONE
                );
            """)

    def save(self, tk: CADTakeoff) -> None:
        self.ensure_schema()
        with self._conn.cursor() as cur:
            cur.execute("""
                INSERT INTO takeoff.cad_takeoffs 
                (id, project_id, drawing_reference, material_code, quantity, unit, created_at)
                VALUES (%s, %s, %s, %s, %s, %s, %s)
                ON CONFLICT (id) DO UPDATE SET
                    quantity = EXCLUDED.quantity;
            """, (
                str(tk.id),
                str(tk.project_id),
                tk.drawing_reference,
                tk.material_code,
                tk.quantity,
                tk.unit,
                tk.created_at
            ))
