-- v1.3 Fleet Management tables
-- Vehicles, maintenance schedules, and maintenance logs

CREATE TABLE IF NOT EXISTS fleet_vehicles (
    id SERIAL PRIMARY KEY,
    branch_id INTEGER REFERENCES branches(id),
    plate VARCHAR(20),
    vin VARCHAR(17),
    make VARCHAR(100),
    model VARCHAR(100),
    year INTEGER,
    current_mileage INTEGER DEFAULT 0,
    fuel_type VARCHAR(20) DEFAULT 'gasolina',
    color VARCHAR(50),
    owner_name VARCHAR(200),
    notes TEXT,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS fleet_maintenance_schedules (
    id SERIAL PRIMARY KEY,
    vehicle_id INTEGER REFERENCES fleet_vehicles(id),
    maintenance_type VARCHAR(100) NOT NULL,
    interval_km INTEGER,
    interval_months INTEGER,
    last_done_at TIMESTAMPTZ,
    last_done_km INTEGER,
    next_due_at TIMESTAMPTZ,
    next_due_km INTEGER,
    notes TEXT,
    is_active BOOLEAN DEFAULT TRUE
);

CREATE TABLE IF NOT EXISTS fleet_maintenance_logs (
    id SERIAL PRIMARY KEY,
    vehicle_id INTEGER REFERENCES fleet_vehicles(id),
    schedule_id INTEGER REFERENCES fleet_maintenance_schedules(id),
    maintenance_type VARCHAR(100),
    mileage_at INTEGER,
    cost NUMERIC(12,2),
    parts_used TEXT,
    employee_id INTEGER REFERENCES employees(id),
    notes TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_fleet_vehicles_plate ON fleet_vehicles(plate);
CREATE INDEX IF NOT EXISTS idx_fleet_maint_vehicle ON fleet_maintenance_schedules(vehicle_id);
CREATE INDEX IF NOT EXISTS idx_fleet_logs_vehicle ON fleet_maintenance_logs(vehicle_id);
