IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = '2025_5bhitn_konstantin_hintermayer_smarter_rentDB')
BEGIN
    CREATE DATABASE [2025_5bhitn_konstantin_hintermayer_smarter_rentDB];
END;
GO

USE [2025_5bhitn_konstantin_hintermayer_smarter_rentDB];
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Customer]') AND type = 'U')
BEGIN
    CREATE TABLE Customer (
        id BIGINT NOT NULL IDENTITY (1, 1),
        [name] VARCHAR(50) NOT NULL,
        Adress VARCHAR(100) NOT NULL,
        driverlicenseid VARCHAR(100) NOT NULL,
        PRIMARY KEY (id)
    );
END;

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Location]') AND type = 'U')
BEGIN
    CREATE TABLE Location (
        id BIGINT NOT NULL IDENTITY (1, 1),
        [name] VARCHAR(250) NOT NULL,
        [address] VARCHAR(250) NOT NULL,
        PRIMARY KEY (id)
    );
END;

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VehicleCategory]') AND type = 'U')
BEGIN
    CREATE TABLE VehicleCategory (
        id BIGINT NOT NULL IDENTITY (1, 1),
        [description] VARCHAR(250) NOT NULL,
        pricePerDay DECIMAL NOT NULL,
        PRIMARY KEY (id)
    );
END;

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Vehicle]') AND type = 'U')
BEGIN
    CREATE TABLE Vehicle (
        id BIGINT NOT NULL IDENTITY (1, 1),
        brand VARCHAR(50) NOT NULL,
        model VARCHAR(50) NOT NULL,
        licensePlate VARCHAR(8) NOT NULL,
        buyDate DATE NOT NULL,
        locationID BIGINT NOT NULL,
        vehicleCategoryID BIGINT NOT NULL,
        PRIMARY KEY (id)
    );

    ALTER TABLE Vehicle
    ADD CONSTRAINT FK_Location_TO_Vehicle FOREIGN KEY (locationID) REFERENCES Location (id);

    ALTER TABLE Vehicle
    ADD CONSTRAINT FK_VehicleCategory_TO_Vehicle FOREIGN KEY (vehicleCategoryID) REFERENCES VehicleCategory (id);
END;

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Rental]') AND type = 'U')
BEGIN
    CREATE TABLE Rental (
        id BIGINT NOT NULL IDENTITY (1, 1),
        rentalStart DATETIME NOT NULL,
        rentalEnd DATETIME NOT NULL,
        actualEnd DATETIME NULL,
        customerID BIGINT NOT NULL,
        vehicleID BIGINT NOT NULL,
        PRIMARY KEY (id)
    );


    ALTER TABLE Rental
    ADD CONSTRAINT FK_Customer_TO_Rental FOREIGN KEY (customerID) REFERENCES Customer (id);

    ALTER TABLE Rental
    ADD CONSTRAINT FK_Vehicle_TO_Rental FOREIGN KEY (vehicleID) REFERENCES Vehicle (id);
END;



