-- Сначала создадим базу данных
CREATE DATABASE transport_company;

-- Переключаемся на базу данных
\c transport_company;

-- Таблица для водителей
CREATE TABLE drivers (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    license_number VARCHAR(50) UNIQUE NOT NULL,
    phone VARCHAR(15),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Таблица для автомобилей
CREATE TABLE vehicles (
    id SERIAL PRIMARY KEY,
    license_plate VARCHAR(20) UNIQUE NOT NULL,
    model VARCHAR(50),
    year INT,
    driver_id INT REFERENCES drivers(id) ON DELETE CASCADE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Таблица для маршрутов
CREATE TABLE routes (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    start_location VARCHAR(100),
    end_location VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Таблица для поездок
CREATE TABLE trips (
    id SERIAL PRIMARY KEY,
    vehicle_id INT REFERENCES vehicles(id) ON DELETE CASCADE,
    route_id INT REFERENCES routes(id) ON DELETE CASCADE,
    driver_id INT REFERENCES drivers(id) ON DELETE CASCADE,
    trip_date TIMESTAMP NOT NULL,
    status VARCHAR(20) CHECK (status IN ('scheduled', 'completed', 'canceled')),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Пример заполнения начальных данных
INSERT INTO drivers (name, license_number, phone) VALUES 
('Иван Петров', 'A1234567', '123456789'),
('Мария Иванова', 'B7654321', '987654321');

INSERT INTO vehicles (license_plate, model, year, driver_id) VALUES 
('ABC123', 'Toyota Camry', 2019, 1),
('XYZ789', 'Honda Accord', 2020, 2);

INSERT INTO routes (name, start_location, end_location) VALUES 
('Маршрут 1', 'Москва', 'Санкт-Петербург'),
('Маршрут 2', 'Казань', 'Екатеринбург');

INSERT INTO trips (vehicle_id, route_id, driver_id, trip_date, status) VALUES 
(1, 1, 1, '2024-07-01 08:00:00', 'scheduled'),
(2, 2, 2, '2024-07-02 09:00:00', 'completed');